【问题标题】:How can i wait for Future in map function?我如何在地图功能中等待未来?
【发布时间】:2020-07-01 23:57:35
【问题描述】:

我的功能在下面,我把错误屏幕截图放在它下面。我尝试了很多东西,但找不到优雅和正确的方法来实现这一点。感谢您的帮助。

**It works**

Future<List<UserLike>> getUserLikedPosts() async {
        return userCollection
            .document(_currentUserId)
            .collection(collection_like)
            .limit(POST_LOAD_LIMIT)
            .getDocuments()
            .then(
          (snapshot) {
            if (snapshot == null) return null;
            return snapshot.documents
                .map((userImage) =>
                    UserLike.fromEntity(UserLikeEntity.fromSnapshot(userImage)))
                .toList();
          },
        );
      }



**It does not work**

Future<List<UserLike>> getUserLikedPosts() async {
    return userCollection
        .document(_currentUserId)
        .collection(collection_like)
        .limit(POST_LOAD_LIMIT)
        .getDocuments()
        .then(
      (snapshot) {
        if (snapshot == null) return null;
        return snapshot.documents.map((userImage) async {
          final postEntity =
              UserLike.fromEntity(UserLikeEntity.fromSnapshot(userImage));

          // NEED TO GET DOWNLOAD URL AND UPDATE MY OBJECT
          final downloadUrl = await FirebaseStorage.instance
              .ref()
              .child("user/${post.userId}/post/${post.file}")
              .getDownloadURL();

          return postEntity.copyWith(downloadUrl: downloadUrl);
        }).toList();
      },
    );
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    我找到了解决方案,也许有人需要它。

     Future<List<UserLike>> getUserLikedPosts() async {
        return userCollection
            .document(_currentUserId)
            .collection(collection_like)
            .limit(POST_LOAD_LIMIT)
            .getDocuments()
            .then(
          (snapshot) async {
            if (snapshot == null) return null;
            return await Future.wait(snapshot.documents.map((userImage) async {
              final post = UserLike.fromEntity(UserLikeEntity.fromSnapshot(userImage));
              final url = await _storageRef.child("user/${post.userId}/post/${post.file}").getDownloadURL();
              return post.copyWith(downloadUrl: url);
            }).toList());
          },
        );
      }
    

    【讨论】:

    • 混合Future API(我的意思是Future.then() 方法)和async / await 东西的原因是什么?如果您的 getUserLikedPosts 方法是 async 则仅使用 await
    • 否则返回可能被 Future----->> 包裹的对象。如果您认为有更好的方法可以做到这一点,请您试一试并告诉我。谢谢
    • 基本上每个return someFuture.then((futureResult) =&gt; somethingElse(futureResult))都可以替换成futureResult = await someFuture; return somethingElse(futureResult);
    • 不,在地图迭代器中,必须使用someFuture.then,否则它会返回未来对象
    猜你喜欢
    • 2021-03-19
    • 2020-10-31
    • 1970-01-01
    • 2020-05-13
    • 2018-03-30
    • 2020-05-06
    • 2014-02-08
    • 2020-02-18
    • 1970-01-01
    相关资源
    最近更新 更多