Sub topic 11
Loading More Items as the User Nears the End
This chapter assumes that you know basic Dart lists and closures, can build a StatefulWidget, and have used ListView.builder. Infinite scrolling means loading another page of data when the user gets close to the end of the current list.
A ScrollController exposes the scroll position of a scrollable. Its extentAfter property reports the number of logical pixels between the bottom of the viewport and the end of the content. When that value becomes small, start loading the next page.
Build a guarded infinite list
The important state has three parts:
- The current items.
- A loading flag that prevents duplicate requests.
- A hasMore flag that stops requests after the final page.
This example simulates a network request. A real application would replace the delay with an API call and usually send a page number or continuation cursor.
import 'package:flutter/material.dart';
class InfiniteFeed extends StatefulWidget {
const InfiniteFeed({super.key});
@override
State<InfiniteFeed> createState() => _InfiniteFeedState();
}
class _InfiniteFeedState extends State<InfiniteFeed> {
final ScrollController _controller = ScrollController();
final List<int> _items = [];
bool _loading = false;
bool _hasMore = true;
@override
void initState() {
super.initState();
_controller.addListener(_onScroll);
_loadMore();
}
void _onScroll() {
if (_controller.position.extentAfter < 300) {
_loadMore();
}
}
Future<void> _loadMore() async {
if (_loading || !_hasMore) {
return;
}
setState(() {
_loading = true;
});
await Future<void>.delayed(const Duration(milliseconds: 700));
if (!mounted) {
return;
}
final start = _items.length;
final newItems = List<int>.generate(20, (index) => start + index);
setState(() {
_items.addAll(newItems);
_loading = false;
_hasMore = _items.length < 100;
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final itemCount = _items.length + (_loading ? 1 : 0);
return ListView.builder(
controller: _controller,
itemCount: itemCount,
itemBuilder: (context, index) {
if (index == _items.length) {
return const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
);
}
return ListTile(
title: Text('Item ${_items[index]}'),
);
},
);
}
}Why the guards matter
The scroll listener can run many times while the user remains near the bottom. Without the loading check, several requests could fetch the same page. Without hasMore, the application could keep requesting data forever after the server has no more results.
The 300-pixel threshold starts the request before the user reaches the end. This gives the request time to finish. Choose the threshold based on network latency and item height. A larger threshold uses more data sooner but reduces visible loading pauses.
The mounted check protects the widget after an asynchronous request finishes. A user might leave the screen while the request is pending. Calling setState on the disposed State object would then cause an error.
Common failure cases
- Put the controller on the same ListView whose position you inspect.
- Dispose the controller in dispose.
- Keep the loading indicator outside the data returned by the server.
- Handle request errors and reset loading to false so a later retry remains possible.
- For refresh, clear the items and reset the pagination cursor before requesting the first page.
Exercise
Why does loadMore check loading before starting a request?
Show answer
The scroll listener may fire repeatedly near the end. The check allows only one request at a time, preventing duplicate pages and unnecessary network work.