Flutter infinite scroll pagination: four bugs I fixed
Flutter infinite scroll pagination bugs from a real app: pages appended twice, a counter skipping ahead, late pages in cleared lists, and prefetching in time.
By Hamza Ghouri
Flutter infinite scroll pagination looks like ten lines of code. Watch the scroll position, fetch the next page near the bottom, append it. On a fitness app I work on, those ten lines hid four bugs across the follow lists: a loading flag that was never set, the same page appended twice, a page counter that skipped ahead, and a late page landing in a list that had been cleared. The community feed had a separate problem, with a spinner users had to wait out at the bottom. This post walks through each one, the fix, and the prefetch rule I use now.
The loading flag nobody set
The lists of another user's Following and Followers had the usual guard at the top of the load method. They checked isLoading before fetching the next page. The check was fine. The problem was that nothing ever set the flag to true.
So the guard always passed. Every scroll end at the bottom of the list, while a page was still loading, fetched that same page again and appended it again. People showed up twice in the list. The Followers list was worse, because it fired on every scroll update at the bottom instead of only on scroll end, so it repeated even more.
This is the classic shape of the bug. A guard that reads a flag looks like protection during review, and it passes every test where only one request happens at a time. Rapid scrolling on a slow connection is the case that exposes it, and that case rarely appears at a developer's desk.
How a page counter skips ahead
The duplicates had a quieter partner. The counter was incremented every time a response arrived. Two overlapping requests for page 3 both come back, the counter moves forward twice, and the next load asks for a page beyond the one it should. So the list did not only repeat rows, its position in the data drifted too.
The cause is that "increment on response" counts responses, and what you actually need to record is which page you now hold. The fix is to work out the page number once, at the moment you request it, and store that exact number when the response lands. Run the same response twice and the counter still says the right thing.
A late page landing in a cleared list
The signed-in user's own Following and Followers lists had two more cases. The guard let a second call through while page 1 was loading, because it made an exception for the first page. And a page still in flight when the list was cleared landed in the new list. Clear the list, and a response that belonged to the old list arrives and gets appended to the fresh one.
A boolean flag cannot catch that. The flag answers "is something loading?", when the question that matters is "is this response still for the list on screen?" The fix was to make each load belong to the list it started on. Take a reference to the list when the load begins, and when the response arrives, compare it with the current list by identity. If they differ, drop the response.
Here is the shape, trimmed and renamed, with all of the fixes in one place:
Future<void> loadNextPage() async {
final list = _list;
if (identical(_loadingList, list) || list.total <= list.items.length) return;
_loadingList = list;
final page = list.currentPage + 1;
try {
final result = await fetchPage(page);
if (!identical(list, _list)) return;
list.items.addAll(result.items);
list.total = result.total;
list.currentPage = page;
} finally {
if (identical(_loadingList, list)) _loadingList = null;
}
}
Clearing the list has to replace the object for this to work, so identical can tell the old one from the new one. Three things changed compared to the usual version. The "in progress" marker is set before the first await and released in finally, so an error cannot leave it stuck. The marker points at a specific list, so a load for the old list does not block the first load for the new one. And the page number comes from the request.
The same idea of late responses landing on the wrong state shows up at a larger scale when a user signs out, which I covered in resetting Riverpod state on logout.
How do I stop Flutter infinite scroll pagination loading the same page twice?
Mark the load as in progress before the first await, and return early from any call that finds a load already running. Work out the page number when you send the request and store that number when the response lands, instead of incrementing on arrival. Tie each load to the list it started on, and drop the response if that list has since been replaced.
Start the next page before the user gets there
The community feed had the opposite problem: it was too cautious. It only asked for the next page when a scroll stopped within 200px of the end. Someone scrolling steadily reached the bottom, the end shimmer kept spinning, and nothing had been requested until they stopped and pushed all the way down.
Now it starts the next page mid-scroll, once about three screens of posts are left. A page takes about 1.3s on staging, and three screens covers that even for a fast scroll. Flutter gives you everything needed in the scroll metrics. extentAfter is the amount of content below the viewport, and viewportDimension is the size of one screen, so the rule measures in screens instead of a fixed pixel count. That holds up across phone sizes. The whole decision fits in one function:
bool shouldLoadNextPage(
ScrollNotification notification, {
required bool isLoading,
required bool hasFailed,
}) {
final metrics = notification.metrics;
if (isLoading || metrics.axis != Axis.vertical) return false;
if (metrics.extentAfter >= metrics.viewportDimension * 3) return false;
return notification is ScrollEndNotification ||
(notification is ScrollUpdateNotification && !hasFailed);
}
Three screens is the right number for that feed at that page time. To pick your own, time a real page load and ask how far a fast flick travels in that time. Heavier pages or slower endpoints need a bigger margin.
Two edge cases in the scroll listener
Moving the trigger into scroll updates means it can now fire many times per second, so two details in that function carry more weight than they look.
After a failed load, only a scroll end retries. Without this rule, a dead connection gets hit on every scroll update for as long as the user keeps moving. A ScrollEndNotification arrives once, when the scroll stops, so a retry happens at a human pace.
Sideways scrolling inside a post is ignored. Scroll notifications bubble up the tree, so a listener around a vertical feed also hears from any horizontal scrollable inside a post. Those metrics describe a different scroll view, and their extentAfter has nothing to do with the feed. Checking metrics.axis filters them out. Without it, swiping through something inside a post could trigger a load, or hold one back.
Test the race, because the happy path passes
All of these bugs live in timing, so a test that awaits each load in turn will pass against the broken code. My default for pagination is to make the fetch replaceable, then hold responses open and release them in the order you want. I would cover at least these cases:
- Two calls while page 2 is in flight produce one request.
- A failed page leaves the list able to load again.
- A list cleared mid-load does not receive the old response.
- The counter matches the last page held after every scenario.
Keeping the scroll rule as a plain function helps too, because you can feed it notifications without pumping a whole feed. For checks that need the real UI, I wrote about letting an AI agent test your Flutter app. And for why green unit tests can sit on top of broken behaviour, see what end-to-end testing found in done tickets.
Client guards are one layer. If duplicates would cost you more than a repeated row on a screen, the database should refuse them as well, which is the approach in fixing race condition duplicate rows with a unique index.
The short version
Most pagination bugs come from treating a load as a yes or no flag. Set the in-progress marker before you await, record the page you requested instead of counting responses, and bind each load to the list it started on. For the feel of the scroll, measure the distance left in screens and start early enough to cover a real page load, retry failures only on a scroll end, and ignore any axis that is not yours.
More of my Flutter and backend work is on the projects page.