Change property of RiverPod StateNotifier state

Viewed 877

When using StateNotifier with Riverpod, how do we notify the change of state whenever we change any property of the state object?

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; 
    }
}    

As you can see from the example above, I need to set "state = state" multiple times to force the change of state object to notify changes on the UI. While this approach kind of works, but I don't think I'm doing it correctly.. Can someone please help me improve this code?

Just trying to get better with Riverpod :)

Thanks!

1 Answers

Simply do it like this

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

if you have an immutable state class with copyWith function do it like this:

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

}

Related