【发布时间】:2021-11-27 23:52:05
【问题描述】:
在使用带有 Riverpod 的 StateNotifier 时,我们如何在更改状态对象的任何属性时通知状态更改?
class UserState {
String name;
int age;
bool isActive;
bool isLoading;
UserState();
}
class UserStateNotifier extends StateNotifier<UserState> {
UserStateNotifier() : super(UserStateNotifier());
void setActive() {
state.isActive = true; // Changing property of state object doesn't refresh UI
state = state; // Need to do this to force the change of state object
}
Future getUserPosts() {
state.isLoading = true;
state = state;
// await userRepo.getUserPosts();
state.isLoading = false;
state = state;
}
}
从上面的例子可以看出,我需要多次设置“state = state”来强制改变状态对象来通知UI上的变化。虽然这种方法可行,但我认为我做得不对。有人可以帮我改进这段代码吗?
只是想通过 Riverpod 变得更好 :)
谢谢!
【问题讨论】: