Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe usage for useScrollController? (Flutter Hooks)

Would the following code be considered safe?

class SomeWidget extends HookWidget {

  @override
  Widget build(BuildContext context) {
    final controller = useScrollController();
    controller.addListener(_someCallback);

    return ...;
  }
}

I'm specifically referring to the addListener. In this ResoCoder hooks tutorial he adds the listener inside the initHook function of a custom hook.

I know that ResoCoder wrote the custom hook to dispose of the scrollController...I'm more curious as to how the controller listener behaves (I have no idea what is allowed and not allowed for listeners). Any resources on where I can learn about them would be great.

Thanks :)

like image 627
Ferdz Avatar asked Jul 10 '26 15:07

Ferdz


1 Answers

Side-effects such as adding listeners should not be done directly inside build. If the widget rebuilt, that would cause the listener to be added again

Instead, you can use useEffect:

final controller = useScrollController();

useEffect(() {
  controller.addListener(_someCallback);
  return () => controller.removeListener(_someCallback);
}, [controller]);

like image 125
Rémi Rousselet Avatar answered Jul 13 '26 19:07

Rémi Rousselet



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!