RIVERPOD SERIES —SEAMLESS INFINITE LIST
Seamless Infinite List with Riverpod in Flutter
Take your list to infinity and beyond! Prevent unnecessary calculations and stops on every page request!
In this article, I’ll talk about how to achieve an infinite list without any holdbacks like a “loading” section at the end of the list or calculating operations like scroll position.
Motivation
Example
This time, I'll try to explain it using code.
Tools
- API: https://catfact.ninja/facts
- HTTP Client: dio
- State Management: riverpod
Models
We have two models in total.
- Cat
- PaginatedResponse
Cat model is pretty straightforward. It only takes a cat fact and fromJson
I didn’t add
toJson
or any other boilerplate, just because we won’t need them in this example.
Also, we have a paginated response model, of course.
API gives us more data, but I only take cats and the total count of the cats, because we only need them to get infinite scroll functionality.
Providers
We have a simple dio provider with baseUrl
to fetch the data.
I also assigned 10 to the page size as a global constant variable.
We also have a paginated cat provider to send paginated requests to the server and convert them into response models.
As you realize, it is a family provider. Instead of adding new items at the end of a cat list. We store every paginated response with a different future provider in the same family. That gives more flexibility and makes the code more manageable.
Also thanks to
riverpod
, it’s caching the data inside and whenever we call the same page again, it gives us the data from the cache and doesn’t send a request to the server in every recall. (you also can control it, tho, when to cache etc.)
In this provider, to get the total count of the cat facts, we send the first request to the server and get the total count of the list.
We need to know the total count of the list to know where to stop the
ListView
.
In order to achieve infinity scroll behavior, we don’t need to listen to scroll events or perform any other complex calculations, ListView.builder
is already giving us the indexes that are going to display, and that’s enough to make pagination requests.
Unlike scroll position calculation, this one is not firing on every scroll movement. It’s only firing when the item needs to be built. It makes it more efficient in this case
The logic is basically like that;
itemBuilder
calls each item when it comes into view, if the data of this item is available, displays it, if it’s not, the next page will be fetched.
Let’s assume that the limit is 4, and after organizing it so that it only pulls 4 data on a page.