Initialize StateProvider in Widget

Issue

I just want initialize provider only one time with widget param. For some reason I can’t use .family. I’m not sure if this is the right way. Can you check this? Thank you.

StateProvider<String> valueStateProvider;

class Widget extends HookWidget {
  final String value;

  Widget({@required this.value}) {
    valueStateProvider = StateProvider<String>((ref) => this.value);
  }
}

Solution

Finally I found the right way to do this. There is special provider type for this situation. ScopedProvider.

final scopedProvider = ScopedProvider<String>((_) => throw UnimplementedError());

class Widget extends HookWidget {
  Widget({@required this.value});
  final String value;

  @override
  Widget build(BuildContext context) {
    return ProviderScope(
      overrides: [scopedProvider.overrideWithValue(this.value)],
      child: AnotherWidget()
     );
  }
}

So you can use scopedProvider in AnotherWidget. Yay!

Answered By – bcihan

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *