I want to use Flutter’s ListView
to display a list of items, and the data of the items are obtained from a RESTful API with pagination support. E.g.
GET /transactions?page=1&limit=100
{
"transactions": [ ... ]
"pagination": {
"total": 1000
}
}
page
: The page to fetch, such as 1, 2, 3, ...
limit
: The size of a page.
total
: Total number of items on the server. It can be large.
I know I can use ListView.builder()
, and let the itemBuilder
callback argument returns a widget wrapped in FutureBuilder
, and call the API asynchronously to fetch page for the index
argument (with some logic caching the pages so that each page is only fetched once).
However, ListView.builder()
also has a itemCount
argument. I don’t know the total count of items before fetching the first page. Without the itemCount
argument, the itemBuilder
may be called with index
exceeding the total number of items.
One way that comes to my mind is to wrap the ListView
in another FutureBuilder
and asynchronously call the API to get the total count. However, the total count may change over time. For example, the total count can be 1000 initially. But when the user scrolls to the end, some items are removed from the server by another user, and the total count becomes 950. When it happens, it’s still possible that itemBuilder
is called with index
out of bound.
What should I do to deal with this situation?
If I understand you well, and from what I can see in the response. you want to do a pagination thing. use infinite_scroll_pagination