Hi i'm new to flutter and asynchronous programming. i need to do something like this:
List<Widget> usersProfiles = [];
getUsers('DcofOiHWcjbjD0i18miW').then((user) {
user.forEach((u) {
usersProfiles.add(new ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage(u.profilePicture),
),
trailing: u.icon,
title: new Text(u.name),
onTap: () {
Navigator.push(context,
new MaterialPageRoute(builder: (context) => new Home()));
},
));
});
});
but usersProfiles
returns null
I'll be very greatful
It could look like following: Future<List<User>> usersFuture = getUsers('DcofOiHWcjbjD0i18miW'); Create the future as member variable so you only fetch once (in case the method initiates a new future each time you call it). And then use it inside a FutureBuilder.
then((value) => value.. add(newFilm)); Another way is if you use await . Here you wait for your future to complete and then add a new value to the list.
In Flutter, the FutureBuilder Widget is used to create widgets based on the latest snapshot of interaction with a Future. It is necessary for Future to be obtained earlier either through a change of state or change in dependencies.
I would recommend either a FutureBuilder or StreamBuilder (for streams) which gives you layout performance benefits and also tools to easily add loading and error widgets. It could look like following:
Future<List<User>> usersFuture = getUsers('DcofOiHWcjbjD0i18miW');
Create the future as member variable so you only fetch once (in case the method initiates a new future each time you call it). And then use it inside a FutureBuilder.
FutureBuilder<List<User>>(
future: usersFuture,
builder: (context, snapshot) {
if(snapshot.connectionState != ConnectionState.done) {
// return: show loading widget
}
if(snapshot.hasError) {
// return: show error widget
}
List<User> users = snapshot.data ?? [];
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
User user = users[index];
return new ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage(user.profilePicture),
),
trailing: user.icon,
title: new Text(user.name),
onTap: () {
Navigator.push(context,
new MaterialPageRoute(builder: (context) => new Home()));
},
);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With