Home > Software engineering >  Pagination with StartAfter not working on a firestore collection group
Pagination with StartAfter not working on a firestore collection group

Time:01-30

I have the below query which keeps returning the same 5 documents on every call, instead of fetching the next group of documents as I would expect.

DocumentSnapshot<Object?>? lastFetchedDoc;

Future<void> getReviews() async {

  Query<Map<String, dynamic>> query = firestore
            .collectionGroup("reviews")
            .where("city", whereIn: ['New York', 'Philadelphia', 'Washington'])
            .orderBy('time_of_posting', descending: true)  // timestamp
            .limit(5);

  if (lastFetchedDoc != null) {
      query.startAfterDocument(lastFetchedDoc!);
  }

  QuerySnapshot snapshot = await query.get();
  lastFetchedDoc = snapshot.docs.last;
}
        

Any ideas what the issue could be here.

Thanks

CodePudding user response:

Calling startAfterDocument returns a new query, so you need to hold on to that return value:

if (lastFetchedDoc != null) {
    query = query.startAfterDocument(lastFetchedDoc!);
}
  • Related