Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to add a listener in the build method in a Stateful widget?

Tags:

flutter

dart

I have a scrollcontroller which I need to add a listener to do some pagination functions on when the user scrolls down on a listview.

Currently, I create the scrollcontroller and a listener in the initState. I'm doing it there, because the scroll controller is actually a PrimaryScrollController and it needs context

var _scrollController = PrimaryScrollController.of(context);

Now I've run into a problem where when my page gets rebuilt for one reason or another the listview will jump to the top.

From what I understand its because on a rebuild, everything is getting rebuild however the initState isn't being run.

SO my solution is to move the scrollcontroller creation into the build method, which seems to be working just fine. However, the listener does not work, unless I also move it into the build method.

Is this ok? Or am I creating potentially many parallel listeners which can increase each time the page gets rebuilt?

like image 869
Mark Avatar asked Dec 18 '25 07:12

Mark


1 Answers

If you are looking to listen to the scroll position and do some operations based on the scroll offset you can try a builder named valueListenableBuilder


ValueListenableBuilder<int>(
              builder: (BuildContext context, int value, Widget? child) {
                return Row(

                  children: <Widget>[
                    Text('$value'),
                    child!,
                  ],
                );
              },
              valueListenable: scrollController.offset,
              child: Container(),
            )


like image 52
Kaushik Chandru Avatar answered Dec 21 '25 03:12

Kaushik Chandru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!