Hannes Hultergård
Hannes Hultergård

Reputation: 1207

Paginate firestore query while still listening to new documents

As many others, I have an app with chat functionality. I have a StreamBuilder<QuerySnapshot> that listens to new chat messages, and a ListView.builder that shows them. I'm looking for a good way to paginate the messages, but none of the solutions I have found works for me, since I always have to listen to new messages.

One of the things I tried was this code, but that didn't seem to work even if the author said he had updated the code.

Each chat message has it's own document in a collection, so right now I just fetch all the documents in the collection and order them by a time field. However this only works for about 20 messages before performance suffers, so I would be very glad if someone could help me with this.

Upvotes: 0

Views: 275

Answers (1)

l1b3rty
l1b3rty

Reputation: 3642

I guess you are showing the messages sorted by creation date, right? Why dont you paginate using the date then?

chatcollectionref.
where("creationdate", "<", enddate)
... // Add more conditions if needed
.orderBy("creationdate","desc").limit(20).get()

Start with enddate far in the future then update it to the creation date of the last message you retrieve and just paginate.

EDIT: a bit more details...

  1. First run of the query: enddate = new Date(2100, 1, 1) and you get the first 20 messages and display them
  2. The user scrolls down and reach the last message
  3. Run again the query: enddate = creationdate of the last message you have already retrieved, and you get the 20 next
  4. Loop back to 2

Works well in my chat app

Upvotes: 3

Related Questions