scrollcontroller flutter example
String message = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Scroll Limit reached"),
),
body: Column(
children: <Widget>[
Container(
height: 50.0,
color: Colors.green,
child: Center(
child: Text(message),
),
),
Expanded(
child: ListView.builder(
itemCount: 30,
itemBuilder: (context, index) {
return ListTile(title: Text("Index : $index"));
},
),
),
],
),
);
}
Once we have our widget, the first step is to declare a ScrollController variable.
ScrollController _controller;
We instantiate it within our initState method, in the following way:
@override
void initState() {
_controller = ScrollController();
super.initState();
}
Then we assign this _controller to our ListView.
ListView.builder(
controller: _controller,
itemCount: 30,
itemBuilder: (context, index) {
return ListTile(title: Text("Index : $index"));
},
)
With this we have our ListView connected with our ScrollController, we just have to listen to the events to determine what we want.
Listening to events
_scrollListener() {
}
@override
void initState() {
_controller = ScrollController();
_controller.addListener(_scrollListener);
super.initState();
}
Now we are listening to the Scroll events, but how we can know if the scroll reach the top or bottom.
We just have to add these validations:
_scrollListener() {
if (_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
setState(() {
message = "reach the bottom";
});
}
if (_controller.offset <= _controller.position.minScrollExtent &&
!_controller.position.outOfRange) {
setState(() {
message = "reach the top";
});
}
}