【发布时间】:2021-04-26 17:51:35
【问题描述】:
我的颤振项目中有一个代码,它计算集合中“已接受”为“待定”的文档数。
QuerySnapshot notifNum = await orders.where("id",isEqualTo:_auth.currentUser.uid).where("accepted",isEqualTo: "pending").get();
然后我列出 QuerySnapshot 中的所有文档并获取它的长度,以获取通知的数量:
List<DocumentSnapshot> _notifc = notifNum.docs;
int notifCount = _notifc.length;
但是,我想让它实时化,这样当文档从“待处理”更新为“已接受”时,通知的数量会自动更新。我尝试使用快照,但它们没有显示任何数字。我怎样才能让它发挥作用?
StreamBuilder<int>(
stream: _orders
.where("ustaId",isEqualTo:_auth.currentUser.uid)
.where("acceptedByUsta", isEqualTo: "pending")
.snapshots().length.asStream(),
builder: (context,snapshot) {
if(snapshot.hasError){
return Text("zzz");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
if(snapshot.hasData){
print("aa");
}else{
print("zzz");
}
return new Positioned(
right: 0,
child: new Container(
padding: EdgeInsets.all(1),
decoration: new BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(6),
),
constraints: BoxConstraints(
minWidth: 15,
minHeight: 12,
),
child: new Text(
"aaa",
style: new TextStyle(
color: Colors.white,
fontSize: 12,
),
textAlign: TextAlign.center,
),
),
);
}),
【问题讨论】:
-
请注意,使用包含读取与查询对应的所有文档的解决方案,每次您想计算它们时,您都需要为所有这些文档的读取付费。如果您有很多文档并经常阅读计数器,这会迅速产生高成本。查看this answer 以查看基于计数器的另一种解决方案。
标签: firebase flutter google-cloud-firestore