当 StateNotifier 与 Riverpod 一起使用时,每当我们更改状态对象的任何属性时,如何通知状态更改?
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 变得更好:)
Thanks!
简单地这样做
void setActive() {
state = state..isActive = true;
}
如果您有一个带有 copyWith 函数的不可变状态类,请执行以下操作:
void setActive(){
state = state.copyWith(isActive: true);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)