0

I have one common state where I need to handle multiple states like the Loading state and Error state.

All other states should have access to both states. So I can re-use these states to base screen and handle those states at single place.

Below is the common state

abstract class CommonState{}
class InitialState extends CommonState{
}

class UnauthorizedState extends CommonState{
}

class LoadingState extends CommonState{
  String? loadingMessage;
  LoadingState({this.loadingMessage});
}

class ErrorState extends CommonState{
  String? errorMessage;
  ErrorState({this.errorMessage});
}

I have added the cubit for the common state as below.

class CommonCubit<S extends CommonState> extends Cubit<S>{
  CommonCubit(S initialState) : super(initialState);
}

I want to use this common cubit and state it everywhere in the app. Can use LoadingState, and ErrorState everywhere. I have tried the below approach but it is not working.

Below is the Login screen state.

class LoginState extends CommonState {}

class UserAuthorized extends LoginState {}

class UserUnauthorized extends LoginState {}

Below is the cubit for the login screen

class LoginCubit extends Cubit<LoginState>{
  LoginCubit() : super( InitialState() ) {
    checkUserAuthorized();
  }

  void checkUserAuthorized() {
    emit(UnauthorizedState());
  }
}

Here, I am getting an error that "The argument type InitialState can't be assigned to the parameter type LoginState. " So not getting how can I achieve this part. Can anyone please help me with this?

Please check above details.

VAB
  • 1

1 Answers1

0

class LoginCubit extends Cubit<LoginState> means that LoginCubit can only emits LoginState itself and subclasses of LoginState.

LoginState is subclass of CommonState and InitialState is subclass of CommonState but they doesn't have any relationships with each other. You can imagine that they are both on same level of "inheritance tree".

To use InitialState in LoginCubit your LoginCubit should extend Cubit<CommonState> (or CommonCubit<CommonState>, seems like common cubit unused at all)

Hope that helps to resolve your issue. However I don't recommend to use common states at all. Please read docs of Flutter block and several articles regarding BLoC. Pretty sure after reading you will change your implementation.

  • I want a common mechanism for the loader and error handling. So I can get rid of adding the same code in multiple places. – VAB Jul 05 '23 at 11:05
  • I have tried your implementation but the issue that I am facing is from the CommonCubit, I can't pass any state apart from the CommonState. Like If I want to emit Loader cubit, I cannot do it. – VAB Jul 05 '23 at 11:06