Basically, I want to set the initial constructor value to StateProvider
so I can use it in its child widgets.
final stateProvider = StateProvider((ref) => "default");
class ExampleWidget extends ConsumerWidget {
ExampleWidget({required String text}){
// how to override default hear as
// stateProvider = text
}
@override
Widget build(BuildContext context, ScopedReader watch) {
return Column(
children: [
Text(watch(stateProvider).state),
Container(
child: ChildWidget(),
),
],
);
}
}
class ChildWidget extends ConsumerWidget {
@override
Widget build(BuildContext context, ScopedReader watch) {
return Container(
child: Text(watch(stateProvider).state),
);
}
}
So how do I implement this?
I have tried this but the state value is not updating.
Edit ----------------
With riverpod_hook
& hooks_flutter
final stateProvider = StateProvider((ref) => "default");
class ExampleWidget extends HookWidget {
@override
Widget build(BuildContext context) {
WidgetsBinding.instance?.addPostFrameCallback((_) {
useEffect((){
context.read(stateProvider).state = "new value";
},[]);
});
final state = useProvider(stateProvider).state;
return Column(
children: [
Text(state),
],
);
}
}
above code throwing this error
Hooks can only be called from the build method of a widget that mix-in
Hooks``
So I tried to initialize under the build method like this
useEffect((){
context.read(stateProvider).state = "new value";
},[]);
but above code throws the following error:
The following Error was thrown building ExampleWidget(dirty, dependencies: [UncontrolledProviderScope]):
Instance of 'Error'
I just want to initialize the value once that's why I want to use useEffect
hook.