【问题标题】:Do cloud firestore snapshot reads all the documents in the collection?云火存储快照是否读取集合中的所有文档?
【发布时间】:2021-01-28 11:35:57
【问题描述】:

我正在创建一个聊天屏幕。我目前正在做的是使用 Streambuilder 来收听“消息”集合并使用 ListView.builder() 显示消息。 下面是我正在使用的代码。

StreamBuilder<QuerySnapshot>(
            stream: _fireStoreInstance
        .collection('$collectionName/$docID/messages')
        .orderBy('sentAt', descending: true)
        .snapshots(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting)
                return Center(
                  child: CircularProgressIndicator(),
                );
              List<Map> documents = snapshot.data.docs
                  .map((doc) => {'documentId': doc.id, ...doc.data()})
                  .toList();

              return ListView.builder(
                cacheExtent: MediaQuery.of(context).size.height,
                reverse: true,
                itemCount: documents.length,
                padding:
                    const EdgeInsets.only(left: 15.0, right: 15.0, bottom: 5.0),
                itemBuilder: (context, index) {
                  
                  return MessageBubble(
                    ...
                  );
                },
              );
            },
          ),

我担心的是,查询会一次性获取集合中的所有文档吗?如果是,那么每次执行查询时都会进行大量读取

_fireStoreInstance
        .collection('$collectionName/$docID/messages')
        .orderBy('sentAt', descending: true)
        .snapshots();

我需要使用 limit 进行分页吗?如果我分页如何收听新消息?感谢您的帮助。

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    是的,.snapshots() 将阅读并继续收听所有符合查询条件的文档,如果您想要其中的一个子集,则必须使用 .limit() 对其进行分页。

    我找到了这个article,其中包含有关如何使用无限滚动使用 Firestore 执行实时分页的逐步视频。我认为这正是您要寻找的,因此我不会发布任何代码,因为您可以按照该示例进行操作。

    【讨论】:

    • 感谢您的回答,是的,最好将您的查询.limit() 以避免不必要的读取。我想出了自己的解决方案,因为不需要为旧聊天添加快照侦听器。相反,只需使用侦听器来收听新消息。
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2012-03-10
    • 2020-07-15
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多