Here is the method to implement pagination for Firestore data in Flutter using ListView:
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) {
//...
},
)
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
});
}
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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-12 11:00:00 +0000
Seen: 16 times
Last updated: Dec 08 '21
How can one obtain live data from interactive broker through API?
What is the reason for the submitted Django form's value being null in the database?
How can we create summary tables by using nested tibbles?
What is the process of moving information from one tab to another in Excel by transposing it?
What does "coxphw undefined columns selected" mean?
Is it not possible to change the data type of an array from 'O' to 'float64'?
How to perform a historical backfill from GA4 into BigQuery?
How can Redux be integrated with Ag-Grid's server-side row model in React?