[英]RiverPod StateNotifier to notify listeners without change to state
[英]Change property of RiverPod StateNotifier state
将 StateNotifier 与 Riverpod 一起使用时,每当我们更改 state object 的任何属性时,我们如何通知 state 的更改?
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”来强制改变 state object 来通知UI上的变化。 虽然这种方法可行,但我认为我做的不正确。有人可以帮我改进这段代码吗?
只是想通过 Riverpod 变得更好:)
谢谢!
简单地这样做
void setActive() {
state = state..isActive = true;
}
如果你有一个不可变的 state class 和 copyWith function 这样做:
void setActive(){
state = state.copyWith(isActive: true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.