嗨,我是Flutter和异步编程的新手。我需要做这样的事情:
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返回null
usersProfiles
null
我会很好
我建议使用FutureBuilder或StreamBuilder(用于流),它可以为您带来布局性能上的优势,还可以提供轻松添加加载和错误小部件的工具。看起来可能如下:
Future<List<User>> usersFuture = getUsers('DcofOiHWcjbjD0i18miW');
将future创建为成员变量,因此您只需提取一次(以防每次调用该方法都会启动一个新的future)。然后在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())); }, ); }); });