'How do I know if there are more documents left to get from a firestore collection?

I'm using flutter and firebase. I use pagination, max 5 documents per page. How do I know if there are more documents left to get from a firestore collection. I want to use this information to enable/disable a next page button presented to the user.

limit: 5 (5 documents each time)

orderBy: "date" (newest first)

startAfterDocument: latestDocument (just a variable that holds the latest document)

This is how I fetch the documents.

collection.limit(5).orderBy("date", descending: true).startAfterDocument(latestDocument).get()

I thought about checking if the number of docs received from firestore is equal to 5, then assume there are more docs to get. But this will not work if I there are a total of n * 5 docs in the collection.

I thought about getting the last document in the collection and store this and compare this to every doc in the batches I get, if there is a match then I know I've reach the end, but this means one excess read.

Or maybe I could keep on getting docs until I get an empty list and assume I've reached the end of the collection.

I still feel there are a much better solution to this.

Let me know if you need more info, this is my first question on this account.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source