What is the solution of initializing things inside consumerWidget as because the initState method is not overridable here?
Riverpod : Alternate way of overriding initState inside ConsumerWidget
24.7k views Asked by towhid At
3
There are 3 answers
6
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
On
I may be late but with the upcoming 1.0.0 of Riverpod you will be able to use https://pub.dev/documentation/flutter_riverpod/1.0.0-dev.2/flutter_riverpod/ConsumerStatefulWidget-class.html and https://pub.dev/documentation/flutter_riverpod/1.0.0-dev.2/flutter_riverpod/ConsumerState-class.html, which does exactly what you want.
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:
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.