I'm trying to implement a infinite scroll functionality.
I tried using a ListView
inside on a NotificationListener
to detect scroll events, but I can't see an event that says if the scroll has reached the bottom of the view.
Which would be the best way to achieve this?
I used NotificationListener that is a widget that listens for notifications bubbling up the tree. Then use ScrollEndNotification , which indicates that scrolling has stopped. For scroll position I used _scrollController that type is ScrollController .
A scroll controller creates a [ScrollPosition] to manage the state-specific to an individual [Scrollable] widget. To use a custom [ScrollPosition], subclass [ScrollController] and override [createScrollPosition]. A [ScrollController] is a [Listenable].
A scroll controller creates a ScrollPosition to manage the state specific to an individual Scrollable widget. To use a custom ScrollPosition, subclass ScrollController and override createScrollPosition. A ScrollController is a Listenable.
There are generally two ways of doing it.
1. Using ScrollController
// Create a variable final _controller = ScrollController(); @override void initState() { super.initState(); // Setup the listener. _controller.addListener(() { if (_controller.position.atEdge) { bool isTop = _controller.position.pixels == 0; if (isTop) { print('At the top'); } else { print('At the bottom'); } } }); }
Usage:
ListView(controller: _controller) // Assign the controller.
2. Using NotificationListener
NotificationListener<ScrollEndNotification>( onNotification: (scrollEnd) { final metrics = scrollEnd.metrics; if (metrics.atEdge) { bool isTop = metrics.pixels == 0; if (isTop) { print('At the top'); } else { print('At the bottom'); } } return true; }, child: ListView.builder( physics: ClampingScrollPhysics(), itemBuilder: (_, i) => ListTile(title: Text('Item $i')), itemCount: 20, ), )
You can use a ListView.builder
to create a scrolling list with unlimited items. Your itemBuilder
will be called as needed when new cells are revealed.
If you want to be notified about scroll events so you can load more data off the network, you can pass a controller
argument and use addListener
to attach a listener to the ScrollController
. The position
of the ScrollController
can be used to determine whether the scrolling is close to the bottom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With