[英]Flutter display collection with subcollection from firestore
我正在開發一個 Flutter 應用程序,該應用程序顯示包含項目的類別列表。 數據取自 firebase。
數據庫結構:
我想顯示這樣的數據,它必須是實時的:
我嘗試使用 Streambuilder,但這只會獲取類別。 有人可以幫助我或指出正確的方向,以獲取項目列表作為每個類別的快照嗎? 提前致謝
快照僅包含字段而不包含集合。 那么我需要另一個具有每個類別的 documentID 的 Streambuilder 嗎? 這似乎需要大量的工作和繁重的數據庫讀取,只是為了獲取已經獲取的項目的集合。
StreamBuilder(
stream: _db.collection('categories').document(widget.id).collection('categories').orderBy('tag', descending: true).snapshots(),
builder: (context, snapshot) {
if(!snapshot.hasData) {
return Loader();
} else {
List<dynamic> docs = snapshot.data.documents;
docs.forEach((element) {
print(element['title']);
print(element.collection('items')); // Does not exist
});
return Text('test');
}
},
Firestore 一次只能從一個集合(或集合組)加載數據。 由於您嘗試從categories
和items
collections 加載數據,因此您至少需要兩個單獨的讀取操作。
StreamBuilder(
stream: _db.collection('categories').document(widget.id).collection('categories').orderBy('tag', descending: true).snapshots(),
builder: (context, snapshot) {
if(!snapshot.hasData) {
return Loader();
} else {
List<dynamic> docs = snapshot.data.documents;
docs.forEach((element) {
print(element['title']);
element.reference.collection('items').get()...
});
return Text('test');
}
},
您需要將get()
調用包裝在FutureBuilder
中,因為它是另一個異步加載操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.