Would the following code be considered safe?

class SomeWidget extends HookWidget {

  Widget build(BuildContext context) {
    final controller = useScrollController();

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

Solution 1: Rémi Rousselet

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(() {
  return () => controller.removeListener(_someCallback);
}, [controller]);