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 :)
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With