Flutter positioned ListView

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, lets 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[ 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; }] ]

Creator of Coflutter.
Founder and Tech Lead at Nextfunc.
Daddy at home.
Love Dart/Flutter, computer science and open source.
Follow him on Twitter, Github, StackOverflow, LinkedIn, Upwork.

Tagged : bottom / dart / event / flutter / listener / listview / scrollable / top

Video liên quan

Chủ Đề