Riverpod : Alternate way of overriding initState inside ConsumerWidget

24.7k views Asked by At

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

3

There are 3 answers

1
Alex Hartford On

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.

6
Vinoth Vino On

Riverpod v2.3.6

You can use ConsumerStatefulWidget and ConsumerState

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

class RiverpodExample extends ConsumerStatefulWidget {
  const RiverpodExample({super.key});

  @override
  ConsumerState<RiverpodExample> createState() => _RiverpodExampleState();
}

class _RiverpodExampleState extends ConsumerState<RiverpodExample> {
  @override
  void initState() {
    super.initState();

    final value = ref.read(helloWorldProvider);
    print(value); // Hello world
  }

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

    return Text(value); // Hello world
  }
}
2
wujek On