Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is the method to implement pagination for Firestore data in Flutter using ListView:

  1. Create a StreamBuilder widget that listens to a stream of Firestore documents. Set the stream property to a function that returns a Query object with appropriate filters and limits for your initial data set.
StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance
      .collection('my_collection')
      .orderBy('timestamp', descending: true)
      .limit(10)
      .snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    //...
  },
)
  1. In the builder function of the StreamBuilder, check if snapshot.hasData is true. If it is, parse the documents in the QuerySnapshot and use them to populate a ListView widget.
if (snapshot.hasData) {
  final documents = snapshot.data.docs;
  return ListView.builder(
      itemCount: documents.length,
      itemBuilder: (BuildContext context, int index) {
        // Build list item
      });
}
  1. In the StreamBuilder, create a ScrollController and listen for the onEndReached event. When this event is fired, load the next set of documents from Firestore and append them to the existing list.
final scrollController = ScrollController();
scrollController.addListener(() {
  if (scrollController.position.extentAfter == 0) {
    FirebaseFirestore.instance
        .collection('my_collection')
        .orderBy('timestamp', descending: true)
        .startAfterDocument(documents[documents.length - 1])
        .limit(10)
        .get()
        .then((value) {
      setState(() {
        documents.addAll(value.docs);
      });
    });
  }
});

return ListView.builder(
    controller: scrollController,
    itemCount: documents.length,
    itemBuilder: (BuildContext context, int index) {
      // Build list item
    });

Note: You will need to manage some state in this implementation. When the new data is loaded from Firestore, you need to append it to the existing list and call setState to trigger a rebuild of the ListView. You will also need to handle cases where there is no more data to load and disable the onEndReached event.