Home > Back-end >  Is there a way to use .startAfter[] with first element on Flutter Firestore?
Is there a way to use .startAfter[] with first element on Flutter Firestore?

Time:09-21

I want to improve my flutterfire methods to request data by groups of 10 to 10. Now I have a method with a limit and start values just to use it as index and I have two requests:

if (start == 0) {
        _subQry = await _db
            .collection('cats')
            .where('isYounger', isEqualTo: true)
            .orderBy('id', descending: true)
            .limit(limit)
            .get();
      } else {
        if (_subQry!.docs.isNotEmpty) {
          final lastVisible = _subQry!.docs[_subQry!.size - 1];
          _subQry = await _db
              .collection('cats')
              .where('isYounger', isEqualTo: true)
              .orderBy('id', descending: true)
              .startAfter([lastVisible.id])
              .limit(limit)
              .get();
        }

I want to improve this code using just one request but the problem is the startAfter[] function which gets the last data of the map list... Is there a way to send to startAfter[] an empty value to get the first element of the collection?

CodePudding user response:

As soon as you call startAfter you have to pass a value to it. There is no value you can pass to make it a non-operation.

But you can use a builder pattern to remove the duplicate code:

var query = await _db
    .collection('cats')
    .where('isYounger', isEqualTo: true)
    .orderBy('id', descending: true)
    .limit(limit);
if (start != 0 && _subQry!.docs.isNotEmpty) {
  final lastVisible = _subQry!.docs[_subQry!.size - 1];
  query = query.startAfter([lastVisible.id])
}
_subQry = query.get();
  • Related