When working with scrollable widgets in Flutter (ListView, SliverList, CustomScrollView…), there is the need to listen to the event when we reach the bottom or the top of the widget. These events can be useful when we want to update UI or execute a logic (Ex: load more data).
In this post, let’s go through a few options to implement these listeners in Flutter
1. Using ScrollController
void setupScrollListener(
{required ScrollController scrollController,
Function? onAtTop,
Function? onAtBottom}) {
scrollController.addListener(() {
if (scrollController.position.atEdge) {
// Reach the top of the list
if (scrollController.position.pixels == 0) {
onAtTop?.call();
}
// Reach the bottom of the list
else {
onAtBottom?.call();
}
}
});
}
// Usage
final ScrollController scrollController = ScrollController();
...
setupScrollListener(
scrollController: scrollController,
onAtTop: () {
print('At top');
},
onAtBottom: () {
print('At bottom');
},
);
2. Using NotificationListener
NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
if (notification.metrics.atEdge) {
if (notification.metrics.pixels == 0) {
print('At top');
} else {
print('At bottom');
}
}
return true;
},
child: ListView.builder(itemBuilder: (BuildContext context) {
return YourItemWidget;
})
)