flutterdartflutter-hooks

How to update the initialData of "useState" from parent in Flutter Hooks


According to the description of useState in flutter_hooks:

... 
/// On the first call, it initializes [ValueNotifier] to [initialData]. [initialData] is ignored
/// on subsequent calls.
...

I want to use useState to change the current widget state. I also want the initialData NOT to be ignored when the value is changed from the parent. How to achieve it?

class MyHookWidget extends HookWidget {
  const MyHookWidget({required this.valueFromParent, super.key});

  final int valueFromParent;

  @override
  Widget build(BuildContext context) {
    final state = useState<int>(valueFromParent);
...

Solution

  • I came cross it by using useEffect or useValueChanged, which is like didUpdateWidget for StatefulWidget.

    useEffect

    Useful for side-effects and optionally canceling them.

    useEffect is called synchronously on every build, unless keys is specified. In which case useEffect is called again only if any value inside keys as changed.

    It takes an effect callback and calls it synchronously. That effect may optionally return a function, which will be called when the effect is called again or if the widget is disposed.

    By default effect is called on every build call, unless keys is specified. In which case, effect is called once on the first useEffect call and whenever something within keys change/

    Example:

    final state = useState<int>(valueFromParent);
    
    useEffect(() {
      state.value = valueFromParent;
      return () {};
    }, [valueFromParent]);
    

    useValueChanged

    Watches a value and triggers a callback whenever the value changed.

    useValueChanged takes a valueChange callback and calls it whenever value changed. valueChange will not be called on the first useValueChanged call.

    useValueChanged can also be used to interpolate Whenever useValueChanged is called with a different value, calls valueChange. The value returned by useValueChanged is the latest returned value of valueChange or null.

    Example:

    final state = useState<int>(valueFromParent);
    
    useValueChanged(
      valueFromParent,
      (_, __) => state.value = valueFromParent,
    );