【问题标题】:Dart - is it possible to change a future.forEach. to a map?Dart - 是否可以更改 future.forEach。到地图?
【发布时间】:2018-12-22 16:58:38
【问题描述】:

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

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

【问题讨论】:

    标签: foreach async-await dart dart-async


    【解决方案1】:

    要将 Future 列表转换为单个 Future,请使用来自 dart:asyncFuture.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"]);
    }));
    

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多