First, you need to make ExploreScreen a StatefulWidget because you need to preserve the state of the scroll controller.
Then, add the following import at the top:
import 'dart:developer';
Next, add a ScrollController property in _ExploreScreenState:
late ScrollController _controller;
Then, add a function called scrollListener(), which is the function callback that will listen to the scroll offsets.
void _scrollListener() {
// 1
if (_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
log('i am at the bottom!');
}
// 2
if (_controller.offset <= _controller.position.minScrollExtent &&
!_controller.position.outOfRange) {
log('i am at the top!');
}
}
Here’s how the code works:
Check the scroll offset to see if the position is greater than or equal to the maxScrollExtent. If so, the user has scrolled to the very bottom.
Check if the scroll offset is less than or equal to minScrollExtent. If so, the user has scrolled to the very top.
Within _ExploreScreenState, override initState(), as shown below:
The framework calls dispose() when you permanently remove the object and its state from the tree. It’s important to remember to handle any memory cleanup, such as unsubscribing from streams and disposing of animations or controllers. In this case, you’re removing the scroll listener.
Hot restart, scroll to the botton and top, and see the printed statements in the Run console:
Performing hot restart...
Syncing files to device iPhone 8...
Restarted application in 1,086ms.
[log] i am at the bottom!
[log] i am at the top!
[log] i am at the bottom!
[log] i am at the top!
Here are some examples of when you might need a scroll controller:
Detect if you’re at a certain offset.
Control the scroll movement by animating to a specific index.
Check to see if the scroll view has started, stopped or ended.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.