[英]Firestore get length data disappear in flutter stream
I make a chat using firebase firestore.我使用 firebase firestore 聊天。
So.所以。 I tried express not read count in the Chat list.
我试过在聊天列表中表示未读计数。
But, Initially the number appears, but it changes to null data.但是,最初出现数字,但它变为空数据。
I don't know Why data chage null data?我不知道为什么数据会更改空数据?
class ChatLength extends StatelessWidget {
const ChatLength({super.key, required this.docId, required this.uid});
final String docId;
final String uid;
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('message_read')
.doc(docId)
.collection('message')
.where('userId', isNotEqualTo: uid)
.where('read', isEqualTo: false)
.snapshots(),
builder: (context, snapshot) {
print(snapshot.data?.size);
if (snapshot.data?.size != null) {
return Container(
child: Text('${snapshot.data?.size}'),
);
} else {
return Container();
}
},
);
}
}
===== Debug console ====
flutter: 1
flutter: null // Data changes to null immediately
I'm trying get a snapshot data from firestore.我正在尝试从 firestore 获取快照数据。
And I put the imported data into the text.我把导入的数据放到文本中。
But Data changes to null immediately.但是 Data 立即更改为 null。
Since you use snapshots()
the code is not just reading the data once, but then continues listening for changes to the data.由于您使用
snapshots()
,因此代码不仅仅是一次读取数据,而是继续监听数据的变化。 So the two values you see mean that the snapshots()
stream was triggered twice, the first time with a single message - and the second time without any messages.因此,您看到的两个值意味着
snapshots()
流被触发了两次,第一次是一条消息,第二次是没有任何消息。
My educated guess is that your code changes the read
value of the document after it gets it, since it has now displayed that message to the user.我有根据的猜测是您的代码在获取文档后更改了文档的
read
值,因为它现在已经向用户显示了该消息。 But doing so means the document no longer meets the criteria of your query, so the snapshots
stream gets a new event without that message in it.但这样做意味着该文档不再符合您的查询条件,因此
snapshots
流将获得一个新事件,其中没有该消息。
Consider using a different mechanism for the query, for example I usually use a timestamp to determine what messages to show.考虑使用不同的查询机制,例如我通常使用时间戳来确定要显示的消息。 Step by step:
一步步:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.