Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh to load new data and scroll to paginate data Flutter Firestore

I have a Firestore collection called 'Feeds' that contains a list of posts for a given user's feed (like Instagram). When the view loads, I call a future and order by time

var userPostsDocumentSnapshot = await _feeds
          .document(userUid)
          .collection(items)
          .orderBy('postDateTime', descending: true)
          .getDocuments();

I was initially using a stream, but when new data is added to the user's feed, I don't want it to show automatically, I want a pull-down-to-load new data. However, I also want to make it efficient by paginating the data as you scroll down (from newest to oldest) to make it a little more efficient. How can I achieve both pull-down-to-load new data and also paginate data when scrolling?

like image 673
Eric Jubber Avatar asked Sep 17 '25 05:09

Eric Jubber


1 Answers

For the pull-down-to-load, you'll just want to execute your query again.

For the pagination, I used a cursor, as documented here. For example, depending on how you're doing the UI, you can limit your query by a particular number of documents.

So for your query, something like this may work:

var userPostsDocumentSnapshot = _feeds
          .document(userUid)
          .collection(items)
          .orderBy('postDateTime', descending: true)
          .limit(10);

Then when you actually grab the documents, store a reference to the last one:

var docsnaps = await userPostsDocumentSnapshot.getDocuments();
var last = docsnaps.docs[documentSnapshots.docs.length-1];

Then when you paginate, use a slight variation on your query:

      ...  _feeds
          .document(userUid)
          .collection(items)
          .orderBy('postDateTime', descending: true)
          .startAfter(last);
like image 94
Jon Mountjoy Avatar answered Sep 19 '25 21:09

Jon Mountjoy