What is the solution of initializing things inside consumerWidget as because the initState method is not overridable here?
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
},
);
}
}