I’m currently developing Android/iOS apps using flutter_riverpod.
And I’m trying to redraw the UI using StateNotifierProvider
.
However, although the state should have been updated, only the UI is not updated.
My StateNotifierProvider
code
Here, user information is managed by StateNotifierProvider
.
final myProvider =
StateNotifierProvider<MyProvider, MyData>(
(ref) => MyProvider(MyData()));
class MyData {
bool myBool = false;
String? text;
}
class MyProvider extends StateNotifier<MyData> {
MyProvider(super.state);
Future<void> update(){
state.myBool = true;
}
}
My ref.read
code
This is called when the user presses a particular button.
void onTapButton() {
ref.read(myProvider).update();
}
My UI code
Here I’m showing a simple UI that shows what’s going on with myBool
in MyData
.
But display false
after pushed button onTapButton()
.
class Main extends ConsumerWidget {
@override
build (context, ref) {
bool b = ref.watch(myProvider).myBool;
return Scaffold(
body: Center(
child: Text(b.toString()), // always false...
),
);
}
}
When I redraw the screen using hot reload, the UI will be updated to show true
.
2
Answers
I solved with freezed package.
StateNotifier need use the setter method
state = MyData()
to notifier to listenersConsider implementing
copyWith
function for yourMyData
so you don’t need to dofinal previousState = state;
like my example. And the state (MyData
) should be immutable.See StateNotifierProvider for more information.