i've been trying to make a listview in flutter and get how many pixels the view had scrolled. Unfortunately, i used NotificationListener
Like this:
NotificationListener<ScrollUpdateNotification>(
child: ListView(
children: [
//content here
],
),
onNotification: (notification) {
//How many pixels scrolled from pervious frame
// print("scrollDelta: ${notification.scrollDelta}");
setState(() {
this.scrollValue = notification.metrics.pixels;
});
//List scroll position
// print("metrics.pixels: ${notification.metrics.pixels}");
return true;
},
),
Issue is that it gave some very poor performance with my application.
So i noticed that you could use a controller directly with the ListView and i made the following code:
ScrollController controller;
controller.addListener(() {
print("i'm here");
});
var scaffold = Scaffold(
backgroundColor: Color(0xFFFFFFFF),
resizeToAvoidBottomPadding: false,
body: Stack(
children: [
ListView(
controller: controller,
children: [
//content here
],
),
],
),
);
But then i get the following error :
NoSuchMethodError: invalid member on null: 'addListener'
I currently have no idea how to get how many pixel were scrolled in a listview without hindering greatly the performances.
Your ScrollController
is initialized as null.
Just give it a value:
ScrollController controller = ScrollController();
Make sure you dispose of it using the dispose
method of your StatefulWidget
.
@override
void dispose(){
controller.dispose();
}
ScrollController controller;
@override
void initState() {
// TODO: implement initState
controller = new ScrollController()..addListener(_scrollListener);
super.initState();
}
void _scrollListener() {
print(controller.position.extentAfter);
if (controller.position.extentAfter < 500) {
// you reached at page bottom
}
}
//////////////////////////
ListView(
controller: controller,
children: [
//content here
],
),
Sorry i forgot to simply initialise it! Now it works but there is still my problem with lag whenever i add a listener.
class Search extends StatefulWidget {
String name;
String location;
Search({
this.name,
this.location,
Key key,
}) : super(key: key);
ScrollController controller = ScrollController();
dispose() {
controller.dispose();
}
@override
_Search createState() => _Search();
}
class _Search extends State<Search> {
widget.controller.addListener(() {
setState(() {
scrollValue = widget.controller.position.pixels;
});
});
/// some unrelated code here
ListView(
controller: widget.controller,
children: [
/// some unrelated code here again
}
whenever i add the addListener the performances drop very harshly
User contributions licensed under CC BY-SA 3.0