flutterdartflutter-bloc

how to use flutter bloc state management efficiently


I'm relatively new to flutter bloc management, earlier I was using Provider state management, I have one question regarding flutter bloc state

Let's assume I'm using Bloc for User related operations or features

There could be following states for User Bloc

abstract class UserState {}

class UserInitialState extends UserState {}

class UserLoadingState extends UserState {}

class UserLoadedState extends UserState {
  final UserModel userModel;
  UserLoadedState({required this.userModel});
}

class UserErrorState extends UserState {
  final String error;
  UserErrorState({required this.error});
}

class UserInvalidFormErrorState extends UserState {
  final String error;
  UserErrorState({required this.error});
}

I emit "UserInvalidFormErrorState" state when user is updating their profile detail and some error appear up due to form validation

the problem is that if I emit "UserInvalidFormErrorState" state, the UserLoadedState is no longer available in the screen where I'm displaying user detail

how to tackle this problem


Solution

  • I suggest you change the structure of your UserLoadedState by combining user data and error messages.

    abstract class UserState {}
    
    class UserLoadedState extends UserState {
      final UserModel userModel;
      final String? error;  // Optional error message
    
      UserLoadedState({
        required this.userModel,
        this.error,
      });
    }
    

    With this structure it avoid you changing the error state when there is a problem with the validation form. You simply emit a new instance of UserLoadedState with the user information and possibly accompanied by a message error if there is any

    void updateUserDetails(UserModel userModel) async {
      try {
        yourValidateUserData(userModel);
        emit(UserLoadedState(userModel: userModel)); // emit without error
      } catch (e) {
        emit(UserLoadedState(userModel: userModel, error: e.toString())); // emit with error
      }
    }
    

    And on the UI side you check if there is an error message in the UserLoadedState state, you display if necessary while keeping the user data