[英]Flutter Firebase Cloud Firestore get stream of list of documents by their ids
Hey guys I have two top level collections, a user and a tabs collection.大家好,我有两个顶级 collections,一个用户和一个选项卡集合。 Within each user document I have an array field of document ids with each element in the array representing a document in the tabs collection (sort of like a reference or a pointer to that document) and I would like to listen to real time changes in the users/document with the list of ID's and to listen for changes to the corresponding documents in the tabs collection.
在每个用户文档中,我都有一个文档 ID 数组字段,数组中的每个元素代表选项卡集合中的一个文档(有点像该文档的引用或指针),我想听取实时变化users/document 与 ID 列表,并监听选项卡集合中相应文档的更改。
Below is my code so far and there are two issues with it.到目前为止,下面是我的代码,它有两个问题。 The stream isn't working client side - I'm not receiving an updated snapshot when I update the document in cloud firestore.
stream 不在客户端工作 - 当我更新云 Firestore 中的文档时,我没有收到更新的快照。 Also in order for me to get a list of tabIds I am currently making a query to cloud firestore which returns a stream however, the whereIn operator only accepts a list of objects so I'm not to sure how to handle that.
此外,为了让我获得 tabId 列表,我目前正在查询 cloud firestore,它返回 stream 但是,whereIn 运算符只接受一个对象列表,所以我不确定如何处理它。
data model screenshot数据 model 截图
Stream<List<Tab>> get tabs {
var tabIds = _db.collection('users').doc(user.uid).snapshots().where((event) => event.get('tabs'));
return _db
.collection('tabs')
.where(FieldPath.documentId, whereIn: tabIds)
.snapshots()
.map((list) =>
list.docs.map((doc) => Tab.fromJson(doc.data())).toList());
}
You can't directly listen to documents based on their ids, but you can add a field called docId
(the value should be the id of the document) to each document then listen to collection with this where condition.不能直接根据文档的id来监听文档,可以给每个文档添加一个名为
docId
的字段(取值应该是文档的id),然后用这个where条件监听集合。
List listOfDocIds = []; // this is the list of your docIds
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('users')
.where('docId', whereIn: listOfDocIds),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.hasError) return Text('Something went wrong');
if (snapshot.connectionState == ConnectionState.waiting)
return CircularProgressIndicator();
List<Map<String, dynamic>> data =
snapshot.data.docs.map((e) => e.data()).toList();
print(data);
// you can build your widget here
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, i) {
return ListTile(
title: Text(data[i]['name']),
// TODO: change 'name' to name of field in users document
);
},
);
},
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.