Sub topic 11
Loading more items as the user nears the end
Infinite scrolling shows a first page of data and fetches the next page when the user approaches the bottom of the list. This chapter assumes you know ListView.builder, ScrollController, and StatefulWidget with setState. It also assumes you can write an async function in Dart.
The idea in one paragraph
A ScrollController exposes a ScrollPosition. That object reports how much content lies before and after the visible area. When the amount after the viewport drops below a threshold, you request the next page and append it to your list. The threshold should be larger than the distance a user can scroll while the request is in flight. If it is too small, the user hits the end and sees a stall.
The metrics you can read
ScrollPosition offers three values that matter here.
| Property | Meaning |
|---|---|
| `extentBefore` | Pixels of content scrolled off the start of the viewport. |
| `extentInside` | Pixels of content currently visible. |
| `extentAfter` | Pixels of content remaining past the end of the viewport. |
You could compare pixels with maxScrollExtent instead. extentAfter is simpler because it already is the difference. In a lazily built list, Flutter estimates the total extent from the items it has built, so extentAfter is approximate until the end is reached. A threshold in pixels is therefore a heuristic, not an exact measure.
The minimal version
This listener appends 20 items whenever fewer than 300 pixels remain.
import 'package:flutter/material.dart';
class Feed extends StatefulWidget {
const Feed({super.key});
@override
State<Feed> createState() => _FeedState();
}
class _FeedState extends State<Feed> {
final ScrollController _controller = ScrollController();
final List<int> _items = List<int>.generate(20, (i) => i);
@override
void initState() {
super.initState();
_controller.addListener(_onScroll);
}
void _onScroll() {
if (_controller.position.extentAfter < 300) {
final start = _items.length;
setState(() {
_items.addAll(List<int>.generate(20, (i) => start + i));
});
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
controller: _controller,
itemCount: _items.length,
itemBuilder: (context, index) {
return ListTile(title: Text('Item ${_items[index]}'));
},
);
}
}This works because the data is local and appears instantly. After setState, the new items push extentAfter back above 300 before the next scroll event. With a network call, the data arrives later. The listener keeps firing on every scroll tick in the meantime, so you would send the same request many times.
What goes wrong with real requests
A scroll listener runs on every change in scroll offset, often once per frame while the user drags or flings. A real loader has to handle these cases:
- Duplicate requests. Use an
_isLoadingflag so only one request runs at a time. - The end of the data. Use a
_hasMoreflag. Without it, you request an empty page on every scroll tick forever. - Failures. If a request throws and you do nothing, the next scroll tick retries immediately. Record the error and stop automatic retries until the user taps a retry button.
- A disposed widget. The user may leave the screen while a request is pending. Check
mountedbefore callingsetState. - A first page that does not fill the screen. No scrolling is possible, so no scroll event fires and the listener never runs. You must check again after each layout.
These cases form a small state machine.
A complete paginated list
The following program runs as is. fetchPage simulates a server that has five pages of 20 items. The last list row is a progress indicator while loading, or a retry tile after an error.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: PagedFeed())));
}
Future<List<int>> fetchPage(int page, int pageSize) async {
await Future<void>.delayed(const Duration(milliseconds: 600));
if (page >= 5) return <int>[];
return List<int>.generate(pageSize, (i) => page * pageSize + i);
}
class PagedFeed extends StatefulWidget {
const PagedFeed({super.key});
@override
State<PagedFeed> createState() => _PagedFeedState();
}
class _PagedFeedState extends State<PagedFeed> {
static const int _pageSize = 20;
static const double _threshold = 300;
final ScrollController _controller = ScrollController();
final List<int> _items = <int>[];
int _nextPage = 0;
bool _isLoading = false;
bool _hasMore = true;
Object? _error;
@override
void initState() {
super.initState();
_controller.addListener(_onScroll);
_loadMore();
}
void _onScroll() {
if (_error != null) return;
if (_controller.position.extentAfter < _threshold) {
_loadMore();
}
}
Future<void> _loadMore() async {
if (_isLoading || !_hasMore) return;
setState(() {
_isLoading = true;
_error = null;
});
try {
final result = await fetchPage(_nextPage, _pageSize);
if (!mounted) return;
setState(() {
_items.addAll(result);
_nextPage++;
_hasMore = result.length == _pageSize;
_isLoading = false;
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted &&
_controller.hasClients &&
_controller.position.extentAfter < _threshold) {
_loadMore();
}
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e;
_isLoading = false;
});
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final showFooter = _isLoading || _error != null;
return ListView.builder(
controller: _controller,
itemCount: _items.length + (showFooter ? 1 : 0),
itemBuilder: (context, index) {
if (index < _items.length) {
return ListTile(title: Text('Item ${_items[index]}'));
}
if (_error != null) {
return ListTile(
title: const Text('Could not load more items'),
trailing: TextButton(
onPressed: _loadMore,
child: const Text('Retry'),
),
);
}
return const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
);
},
);
}
}How it handles each case
_loadMorereturns at once if a load is running or the data is exhausted, so many listener calls produce one request._hasMorebecomes false when a page is shorter than_pageSize. The simulated server returns an empty page at the end, which also sets it to false. Here a full last page costs one extra request._onScrollskips automatic loading while_erroris set. Only the Retry button calls_loadMoreagain, and it clears the error first.- The post-frame callback runs after the new items are laid out. If they still do not fill the viewport, it loads again. This covers the case where there is no scrolling to trigger the listener.
- The footer row is part of
itemCount, so the spinner and retry tile scroll with the content.
Choosing a trigger
| Trigger | Fires when | Notes |
|---|---|---|
| `ScrollController` listener | The offset changes | Needs a controller you own and dispose. Gives access to `position`. |
| `NotificationListener<ScrollNotification>` | A scrollable below it notifies | No controller needed. `notification.metrics.extentAfter` has the same values. Return `false` so the notification keeps bubbling. |
| Check in `itemBuilder` | An item near the end is built | Ties loading to item count. Fine for lists, awkward for a `SliverList` mixed with other content. |
The same approaches work for GridView.builder, because it accepts a controller and builds lazily. Reversed lists such as chat screens also work. With reverse: true, the end of the scroll direction is the visual top, and extentAfter still measures toward it. That is where older messages load.
Common mistakes
- Using the data length as the page number. If items get filtered or deduplicated, the count no longer matches the page. Keep a separate page counter or a server cursor.
- Forgetting
dispose. The controller keeps its listeners and any attached position alive. Dispose it with theState. - Calling
positionbefore it is attached._controller.positionthrows if no scrollable is using the controller. CheckhasClientsoutside listeners, as the post-frame callback does. - Mixing in pull to refresh without resetting. A refresh must clear
_items, set_nextPageto 0, set_hasMoreto true, and clear_error. Otherwise the list appends page 0 data after old data. - Calling
setStateafter anawaitwithout checkingmounted. This throws when the user has left the screen.
Exercise
The first page returns only 5 items, and each item is 56 pixels tall on a screen that shows 800 pixels. With only a scroll listener, why does the list never load page two? What in the complete example fixes this?
Show answer
The 5 items occupy 280 pixels, so the list cannot scroll and no scroll events occur. The listener never runs. The post-frame callback in _loadMore fixes this. After the first page is laid out, it checks extentAfter, finds it is below the threshold, and calls _loadMore again. It repeats until the viewport is filled or _hasMore becomes false.
Exercise
A user flings the list to the bottom, and the network request fails. Describe what the user sees and which variable stops the listener from retrying on every frame.
Show answer
The footer changes from a progress indicator to a tile with the message "Could not load more items" and a Retry button. The _error field is non-null, and _onScroll returns early when it is set, so the listener sends no more requests. Tapping Retry calls _loadMore, which clears _error and starts a new request.