更改 属性 的 RiverPod StateNotifier 状态
Change property of RiverPod StateNotifier state
在 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 变得更好 :)
谢谢!
就这么干
void setActive() {
state = state..isActive = true;
}
如果你有一个不可变的状态 class 带有 copyWith 函数,这样做:
void setActive(){
state = state.copyWith(isActive: true);
}
在 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 变得更好 :)
谢谢!
就这么干
void setActive() {
state = state..isActive = true;
}
如果你有一个不可变的状态 class 带有 copyWith 函数,这样做:
void setActive(){
state = state.copyWith(isActive: true);
}