Flutter, Firestore pagination and realtime update
So much buzz words on a title, impressive yeah ?
Comments on application are a common use case, problems starts when you want an infinite list while keeping real times update.
Lets splits up the problem:
- I want to keep riverpod to handle my state, update my UI if new data come;
- A view model (an external controller) will be responsible to collect data
- Firestore allow realtime update through streams
Riverpod State
If you are used we Riverpod, nothing new here. We create a FutureProvider, to trigger async function;
We create a commentBloc which is an external controller, to split ui view/controller.
Dont forget to set up also dispose method, to cancel subscriptions for example.
Finally return it, to trigger later a fetchMore()
commentBloc, an externam controller
documentList allow us to store documents from firestore. We need to store them as DocumentSnapshot to enable pagination.
fetchFirstList() set up a stream for listening real update.
fetchNextPosts() allow infinite list, and trigger fetch more data. To paginate, we pass the last document we get with fetchFirstList()(documentList[documentList.length — 1] and .startAfterDocument(documentSnapshot))
Dont forget to complete dispose
Listening for realtime updates
Its during first call in fetchFirstList() that we set up stream with firestore.
To set up a stream with firestore, we used the .snapshots() (easy hum ?)
To get realtime update from a firestore stream, we set up a StreamSubscription that will be wake up each time something new happen in our stream.
Change type allow us to know what kind of change happen.
Everything is set up now.