在 Flutter Firestore 中等待 Future<DocumentSnapshot> 的结果

Pur*_*rus 4 dart firebase flutter google-cloud-firestore

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

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

以下是我从图像集合中获取文档的方法。

    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;
      }
    }
Run Code Online (Sandbox Code Playgroud)

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

但是用户值被延迟检索并且没有与 post 对象一起返回。

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

die*_*per 6

那是因为该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;
  }
Run Code Online (Sandbox Code Playgroud)

我建议您将其称为FutureBuilder