飞镖-是否有可能改变future.forEach。到地图上?

时间:2018-07-14 13:20:42

标签: foreach async-await dart dart-async

所以基本上我有这段工作代码:

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;

它可以正常工作,并且完全满足我的需要,但是我想知道是否有办法将其更改为地图,例如:

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

我这样做的问题是它说:无法将List >类型的值赋给List 类型的变量。

所以我想知道是否有可能,或者唯一的方法是使用Future.forEach

1 个答案:

答案 0 :(得分:4)

要将期货列表变成单个期货,请使用dart:async中的Future.wait。 (也不要忘记返回用户对象)。

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"]);
}));