如何从Firebase ' get() '中获取' DocumentReference '



我有一个集合ads,其中包含一个DocumentReference作为ownerId

使用下面的代码,我可以获取最近的10个广告作为List<Ad>:

/// Returns a list of ads of the given [category]
static Future<List<ClassifiedAd>> getFromCategory(
ClassifiedAdCategory category,
{int max = 10}) async {
return FirebaseFirestore.instance
.collection('ads')
.where('category', isEqualTo: category.name)
.orderBy('creationDate', descending: true)
.limit(max)
.get()
.then((snapshot) {
return snapshot.docs.map((doc) {
final data = doc.data();
return Ad.fromMap(data);
}).toList();
});

但现在我想从我上面谈论的DocumentReference中获取所有者(collection users)。但我对如何做到这一点很困惑。

修改后的代码无法编译:

返回类型'List'不是'FutureOr',这是闭包上下文所要求的。

/// Returns a list of ads of the given [category]
static Future<List<ClassifiedAd>> getFromCategory(
ClassifiedAdCategory category,
{int max = 10}) async {
return FirebaseFirestore.instance
.collection('ads')
.where('category', isEqualTo: category.name)
.orderBy('creationDate', descending: true)
.limit(max)
.get()
.then((snapshot) {
// <<<< Error starts right here down to the removeWhere()
return snapshot.docs.map((doc) {
final data = doc.data();
final DocumentReference docRef = data["ownerId"];

return docRef.get().<ClassifiedAd?>then((snapshot) {
if (snapshot.exists) {
return ClassifiedAd.fromMap(data);
}
return null;
});
}).toList()
// Don't take into account potential nulls
..removeWhere((a) => a == null);
});

我该怎么做呢?

我会说你正在做的错误的事情是你试图在map()方法内异步获取快照,这是同步的,对于像你这样的情况,我建议使用await/async并且在你保证得到它之前不返回任何东西,尝试这个:

static Future<List<ClassifiedAd>> getFromCategory(
ClassifiedAdCategory category,
{int max = 10}) async {
final snapshot = await FirebaseFirestore.instance
.collection('ads')
.where('category', isEqualTo: category.name)
.orderBy('creationDate', descending: true)
.limit(max)
.get();
List<ClassifiedAd> result = [];
for (int index = 0; index < snapshot.docs.length; index++) {
final doc = snapshot.docs[index];
final data = doc.data();
final DocumentReference docRef = data["ownerId"];
final docOwnerSnapshot = await docRef.get();
if (docOwnerSnapshot.exists) {
result.add(ClassifiedAd.fromMap(data));
}
}
return result;
}

最新更新