Safe usage for useScrollController? (Flutter Hooks)

3.4k views Asked by At

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 :)

1

There are 1 answers

1
Rémi Rousselet On

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]);