Pagination retrieves a collection in parts. The user interface can request another page near the end of a list, but the repository and state model must decide whether that request is currently valid.
Track separate states
Initial loading, later-page loading and a later-page failure are different experiences. A failed second page should not erase the first page’s usable content.
The following pseudocode-like Dart fragment belongs in a feature model. repository, items, cursor, hasMore and notifyListeners are members supplied by the project. The repository returns a typed page.
Worked example
This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.
Future<void> loadNext() async {
if (isLoading || !hasMore) return;
isLoading = true;
notifyListeners();
try {
final page = await repository.fetchPage(cursor);
items = [...items, ...page.items];
cursor = page.nextCursor;
hasMore = cursor != null;
pageError = null;
} catch (error) {
pageError = error;
} finally {
isLoading = false;
notifyListeners();
}
}
Read the result
The request guard prevents repeated scroll events from launching duplicate work. A real feature should also handle cancellation or stale responses when the query changes. Deduplicate by stable item identity if the API can overlap pages.
Walk through a second-page failure
The first page remains in items. A request for another page sets isLoading before awaiting the repository. A second scroll trigger sees that flag and returns, preventing duplicate work. If the request fails, the existing items stay usable and pageError describes only the incremental load failure.
On a successful retry, append the returned items once and advance the cursor. If the search or filter changed while a request was pending, use request identity or cancellation so the old page cannot append to a new query’s collection.
The list builder controls widget construction; it does not supply this request contract. Test pagination with a fake repository so you can force overlapping requests and later-page failures reliably.
Practice and verification
Simulate two scroll events before the first request completes. Verify only one repository call occurs. Fail a later page, retry it and ensure previous items remain visible without duplication.