flutter_hooks icon indicating copy to clipboard operation
flutter_hooks copied to clipboard

Expose keys in `useState`

Open timcreatedit opened this issue 6 months ago • 5 comments

Is your feature request related to a problem? Please describe. Multiple times now I've been surprised by the fact that useState doesn't allow for setting custom keys that trigger a reevaluation of the state. A simple use-case is rebuilding a widget whenever a PageController page changes.

Widget build(BuildContext context) {
    final page = useState(pageController.initialPage);
    return PageView(
       controller: pageController,
       onPageChanged: (value) => page.value = value,
      //  ...
    );
}

This code works in principle, until pageController changes. This change will not get picked up by useState.

Describe the solution you'd like Add optional keys to the useState hook.

final page = useState(pageController.initialPage, keys: [pageController]);
// ...

Describe alternatives you've considered For the given example, one might suggest useListenable, but that will rebuild way too often.

Another option would be:

useEffect(() {
  page.value = pageController.initialValue;
}, [pageController]);

However, this is verbose, imperative, and not really readable (it might also add an extra rebuild?).

Additional Context: Riverpods StateProvider is a nice example for a bridge between declarative re-evaluation using ref and imperative modification using .state

timcreatedit avatar Aug 12 '24 17:08 timcreatedit