[英]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.