To implement Lazy Loading (also called infinite scrolling) in your Flutter widget using a ScrollController, you need to listen to scroll events and detect when the user is near the bottom of the list. At that point, you trigger loading more data.
Here’s a complete example pattern you can integrate into your widget:
✅ 1. Accept the ScrollController from parent:
Make sure your widget uses the passed widget.scrollController.
✅ 2. Add a listener in initState():
@override
void initState() {
super.initState();
widget.scrollController.addListener(_onScroll);
}
✅ 3. Define the scroll handler:
void _onScroll() {
if (widget.scrollController.position.pixels >= widget.scrollController.position.maxScrollExtent - 200) {
_loadMore(); // or call your passed function
}
}
- 200means you start loading more before reaching the end. Adjust this to your needs.
✅ 4. Create the lazy loading function:
bool _isLoadingMore = false;
void _loadMore() async {
if (_isLoadingMore) return;
setState(() {
_isLoadingMore = true;
});
// Call your data loading logic here, maybe a passed callback
await fetchMoreData(); // await your async data load
setState(() {
_isLoadingMore = false;
});
}
You may also add additional checks for – not having more data.
✅ 5. Add a loading indicator at the bottom (optional):
In your ListView.builder:
itemCount: items.length + (_isLoadingMore ? 1 : 0),
itemBuilder: (context, index) {
if (index < items.length) {
return ListTile(title: Text(items[index]));
} else {
return const Padding(
padding: EdgeInsets.all(16.0),
child: Center(child: CircularProgressIndicator()),
);
}
}
Read more about Flutter Scroll Explained.
