本文介绍了从未来中返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是flutter和异步编程的新手。我需要执行以下操作:
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()));
},
));
});
});
但 usersProfiles
返回空
我会非常感激
推荐答案
我建议使用或(适用于流),它为您带来了布局性能上的优势,并提供了轻松添加负载的工具和错误小部件。
看起来可能像这样:
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');
将future创建为成员变量,因此您只需提取一次(以防方法每次都启动一个新的future)您称呼它的时间)。然后在FutureBuilder中使用它。
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()));
},
);
});
});
这篇关于从未来中返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!