Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

firebase - Do cloud firestore snapshot reads all the documents in the collection?

I'm creating a chat screen. What I'm currently doing is that I'm using a Streambuilder to listen to the 'messages' collection and display the messages using ListView.builder(). Below is the code i'm using.

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(
                    ...
                  );
                },
              );
            },
          ),

My concern is, will the query fetch all the documents in the collection all at once? If yes then it will be a lot of reads each time the query is executed

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

Do I need to paginate by using limit ? If I paginate how do I listen to new messages ? Thank you for your help.

question from:https://stackoverflow.com/questions/65936340/do-cloud-firestore-snapshot-reads-all-the-documents-in-the-collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, .snapshots() will read and keep listening to all documents that fit the query, if you want a subset of that you will have to paginate it using .limit().

I have found this article, with a video step by step on How to perform real-time pagination with Firestore with the use of an infinite scroll. I think this is exactly what you looking for, so I won't post any code since you can follow that example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...