简体   繁体   中英

return a list from a future in 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()));
            },
          ));
        });
      });

but usersProfiles returns null

I'll be very greatful

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()));
            },
          );
      });
  });
Future<Solution> JuniorDeveloperQuestion {
// use Expansion List with Dynamic Data
return _2021.Solution.ExpansionListWithDynamicData; 
}

https://dev.to/rrtutors/dynamic-expansiontile-create-expansion-list-with-dynamic-data-2hl3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM