【问题标题】:Waiting for result of Future<DocumentSnapshot> in Flutter Firestore在 Flutter Firestore 中等待 Future<DocumentSnapshot> 的结果
【发布时间】:2019-01-25 09:23:28
【问题描述】:

我有一个包含 2 个字段的云 FireStore 数据库。

  • imageUrl(远程文件的url)
  • user(用户集合中文档的参考字段)

以下是我如何从图像集合中获取文档。

    class ImagePost {

      final String imageUrl;

      final User user;

      const ImagePost(
          {this.imageUrl,
          this.user});

      factory ImagePost.fromDocument(DocumentSnapshot document) {
        User userInfo;

        DocumentReference userReference = document['user'];
        Future<DocumentSnapshot> userRef = userReference.get();

       userRef.then((document) {
          userInfo = User.fromJSON(document.data);
        });

        ImagePost post = new ImagePost(
          imageUrl: document['imageUrl'],
          user: userInfo // ==> always null while returning
        );

        return post;
      }
    }

在获取参考用户文档时,post 对象始终包含用户字段的空值。我希望填充用户对象。

但用户值检索较晚,没有与帖子对象一起返回。

如何确保在返回帖子值之前检索到用户值?

【问题讨论】:

标签: firebase dart flutter google-cloud-firestore


【解决方案1】:

这是因为 get() 方法返回一个 Future 并且您需要使用 async 'await' 来等待响应,但不能在您的 constructor 中使用它。

只需创建一个方法(不是构造函数)并像这样使用:

  Future<ImagePost> getImagePostFromDocument(DocumentSnapshot document) async {
    DocumentReference userReference = document['user'];
    DocumentSnapshot userRef = await userReference.get();
    User userInfo = User.fromJSON(userRef);
    ImagePost post = new ImagePost(
        imageUrl: document['imageUrl'],
        user: userInfo 
        );
    return post;
  }

我建议您将其称为FutureBuilder

【讨论】:

  • 它有帮助。有没有更好的方法来避免第二次远程调用来获取每个项目的用户详细信息?
  • 您可以将其放在另一个问题中,以便发布您拥有的代码。现在我的回答对你有帮助,将其标记为已解决以避免误解。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-09-29
  • 2020-08-04
  • 2021-10-16
  • 2020-07-02
  • 2021-02-26
  • 2019-11-05
  • 2021-01-10
  • 1970-01-01
相关资源
最近更新 更多