[英]Get all documents from a Firestore collection in Flutter
我嘗試了不同的方法,但我無法編輯代碼結構
//First way
QuerySnapshot querySnapshot = await db.firestoreInstance.collection('user-history').get();
var list = querySnapshot.docs;
print('MY LIST ===== $list');
//Second way
final CollectionReference collectionRef = db.firestoreInstance
.collection(historyCollection);
print('MY SECOND LIST ===== $list');
collectionRef.get().then((qs) {
qs.docs.forEach((element) {
print('MY doc id ${element.id}');
});
});
在我的 firebase 集合(historyCollection)中,我有四個文檔,但調試器返回空數組 []。 還有另一種方法可以通過 flutter 調用某個集合中的所有文檔嗎? 我正在嘗試通過 FutureBuilder 組件調用此方法。
我的firestore版本是:“cloud_firestore:^0.16.0+1”
整個問題不在於這些代碼片段。 這個問題是因為我的 collections 有子集合。 我讀到了這個,我知道子集合可以在沒有他們的祖先的情況下生存,訪問父母的唯一方法是直接指定文檔的確切路徑和名稱。 要在我的情況下使用此代碼,需要添加我的整套 collections 的虛擬組件。 有關更多信息,請查看以下兩個主題:
這應該可以解決問題:
Future<List<dynamic>> getCollection(CollectionReference collection) async {
try {
QuerySnapshot snapshot = await collection.get();
List<dynamic> result = snapshot.docs.map((doc) => doc.data()).toList();
return result;
} catch (error) {
print(error);
return null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.