【问题标题】:Change property of RiverPod StateNotifier state更改 RiverPod StateNotifier 状态的属性
【发布时间】: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 变得更好 :)

谢谢!

【问题讨论】:

    标签: flutter riverpod


    【解决方案1】:

    简单地这样做

    void setActive() {
            state = state..isActive = true;
        }
    

    如果您有一个带有 copyWith 函数的不可变状态类,请这样做:

    void setActive(){
        state = state.copyWith(isActive: true);
    

    }

    【讨论】:

    • 这行得通,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2021-10-28
    • 2021-04-21
    • 2021-08-11
    • 2023-02-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多