Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - is it possible to change a future.forEach. to a map?

So basically i have this piece of working code:

List<User> users = List();
await Future.forEach(querySnapshot.documents, (doc) async {
  final snapshot = await doc['user'].get();
  users.add(User(id: snapshot["id"], name: snapshot["mail"]));
});

return users;

It's working fine and does exactly what I need but I was wondering if there was a way to somehow change it to a map, such as:

return querySnapshot.documents.map((doc) async {
  final snapshot = await doc['user'].get();
  User(id: snapshot["id"], name: snapshot["mail"]);
}).toList{growable: true};

The problem when I do that is that it says: a value of type List< Future< Null>> can't be assigned to a variable of type List< User>.

So I was wondering if it was possible or if the only way is with a Future.forEach

like image 520
Neodigi Avatar asked Sep 07 '25 01:09

Neodigi


1 Answers

To turn a list of Futures into a single Future, use Future.wait from dart:async. (Also don't forget to return the user object).

final List<User> = await Future.wait(querySnapshot.documents.map((doc) async {
  final snapshot = await doc['user'].get();
  return User(id: snapshot["id"], name: snapshot["mail"]);
}));
like image 163
Jonah Williams Avatar answered Sep 09 '25 17:09

Jonah Williams