Riverpod : Alternate way of overriding initState inside ConsumerWidget

Viewed 12453

What is the solution of initializing things inside consumerWidget as because the initState method is not overridable here?

3 Answers

Updated

Riverpod v1.0.0

You can use ConsumerStatefulWidget and ConsumerState

final helloWorldProvider = Provider((_) => 'Hello world');

class RiverpodExample extends ConsumerStatefulWidget {
  @override
 _RiverpodExampleState createState() => _RiverpodExampleState();
}

class _RiverpodExampleState extends ConsumerState<Example> {

  @override
  void initState() {
    super.initState();

    final value = ref.read(helloWorldProvider);

  }

  @override
  Widget build(BuildContext context) {
    final value = ref.watch(helloWorldProvider);

    return Text(value); // Hello world
  }
}

Up to Riverpod v0.14.0+3

You have to use StatefulWidget and return Consumer as a root widget from the build method.

Consumer

Consumer can be used to listen to providers inside a StatefulWidget or to rebuild as few widgets as possible when a provider updates.

final helloWorldProvider = Provider((_) => 'Hello world');

class RiverpodExample extends StatefulWidget {
  @override
  _RiverpodExampleState createState() => _RiverpodExampleState();
}

class _RiverpodExampleState extends State<Example> {

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, watch, child) {
        final value = watch(helloWorldProvider);
        return Text(value); // Hello world
      },
    );
  }
}

I'm not totally sure how to answer your question as I have not worked with ConsumerWidget. I'd presume the idea is to keep most of your state in providers.

However, I would like to recommend using hooks_riverpod alongside flutter_hooks (same developer).

This makes keeping state local to the widget simple and also provides easy access to providers.

For example:

class Example extends HookWidget {
  const Example({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final test = useProvider(Test.provider());

    final controller = useTextEditingController();
    final loading = useState(false);
    final buttonText = useState('Change me!');

    return Column(
      children: [
        TextField(controller: controller),
        if (!loading) RaisedButton(
          onPressed: () async {
            loading.value = true;
            await Future.delayed(const Duration(seconds: 1));
            buttonText.value = controller.text;
            loading.value = false;
          }
          child: Text(buttonText.value),
        ),
        if (loading) const CircularProgressIndicator(),
        // Do something with providers, etc.
      ],
    ),
  );
}

Just a quick example, but there are plenty of resources (flutter_hooks, hooks_riverpod) to help you along. Also, check out examples from the developer on riverpod hooks usage.

Related