[英]Flutter display collection with subcollection from firestore
I am working on a Flutter application that displays a list of categories with items inside.我正在开发一个 Flutter 应用程序,该应用程序显示包含项目的类别列表。 the data is fetched from firebase.数据取自 firebase。
Database structure:数据库结构:
I want to show data like this and it has to be real time:我想显示这样的数据,它必须是实时的:
I tried to use Streambuilder, but this only fetches the categories.我尝试使用 Streambuilder,但这只会获取类别。 Could someone help me or point me in the right direction to also get the list of items as a snapshot for each category?有人可以帮助我或指出正确的方向,以获取项目列表作为每个类别的快照吗? Thanks in advance提前致谢
A snapshot only contains the field and not the collection.快照仅包含字段而不包含集合。 So do I need another Streambuilder with the documentID of each category?那么我需要另一个具有每个类别的 documentID 的 Streambuilder 吗? This seems like a lot of work and heavy database reads, just to get the collection of an item already fetched.这似乎需要大量的工作和繁重的数据库读取,只是为了获取已经获取的项目的集合。
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 can only load data from one collection (or collection group) at a time. Firestore 一次只能从一个集合(或集合组)加载数据。 Since you're trying to load data from the categories
and items
collections, you will need at least two separate read operations.由于您尝试从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');
}
},
You'll need to wrap the get()
call in a FutureBuilder
, since it's another asynchronous load operation.您需要将get()
调用包装在FutureBuilder
中,因为它是另一个异步加载操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.