我有一个包含 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
对象始终包含用户字段的空值。我希望填充用户对象。
但用户值检索较晚,没有与帖子对象一起返回。
如何确保在返回帖子值之前检索到用户值?
最佳答案
那是因为 get()
方法返回一个 Future 并且你需要使用 async
'await' 来等待响应,但是不能使用它在你的构造函数
中。
只需创建一个方法(不是构造函数)并像这样使用:
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
关于firebase - 在 Flutter Firestore 中等待 Future<DocumentSnapshot> 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51910549/