fetchPaginatedDocuments method
Fetches paginated documents from the Firestore collection.
limit
defines the maximum number of documents to fetch.
lastDocument
is the last document from the previous page used to fetch the next page.
Returns a Future containing a Map with the list of documents and the last document fetched.
Implementation
Future<PaginationResult> fetchPaginatedDocuments({
int limit = 10,
DocumentSnapshot? lastDocument,
String orderByField = 'createdAt',
}) async {
final now = DateTime.now();
loggerService?.log("⌛ Fetching paginated documents in progress");
try {
Query query = firestoreReadService
.getCollectionReference(collection)
.orderBy(orderByField)
.limit(limit);
if (lastDocument != null) {
query = query.startAfterDocument(lastDocument);
}
final querySnapshot = await query.get();
final List<Map<String, dynamic>> documents = querySnapshot.docs
.map((doc) => doc.data() as Map<String, dynamic>)
.toList();
// Get the last document to use for pagination in the next call
final QueryDocumentSnapshot<Object?>? lastDoc =
querySnapshot.docs.isNotEmpty ? querySnapshot.docs.last : null;
return PaginationResult(documents, lastDoc);
} catch (e) {
const errorMessage = 'Error fetching paginated documents';
loggerService?.logError(errorMessage, e.toString());
rethrow;
} finally {
loggerService?.logCompletionTime(now, 'Fetching paginated documents');
}
}