在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变得更好:)
谢谢!
发布于 2021-10-08 18:32:34
简单地这样做就可以了
void setActive() {
state = state..isActive = true;
}
如果你有一个带有copyWith函数的不可变状态类,可以这样做:
void setActive(){
state = state.copyWith(isActive: true);
}
https://stackoverflow.com/questions/69488768
复制相似问题