简体   繁体   English

Firestore 获取长度数据在颤振流中消失

[英]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
  1. I'm trying get a snapshot data from firestore.我正在尝试从 firestore 获取快照数据。

  2. And I put the imported data into the text.我把导入的数据放到文本中。

  3. 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:一步步:

  • Ensure each message document has a timestamp field.确保每个消息文档都有时间戳字段。
  • For each user store (either in the database or in local storage of the app) when they last started the app.对于每个用户上次启动应用程序的存储(在数据库中或在应用程序的本地存储中)。
  • Then request from the database the messages since they last started the app.然后从数据库请求自他们上次启动应用程序以来的消息。
  • Make sure to start the query before you update the timestamp value, otherwise you'll never get any results.确保在更新时间戳值之前启动查询,否则您将永远得不到任何结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM