Search code examples
flutterdartbloccubit

Bad condition - Cubit


I'm trying to get to the RegistrationSendCode screen. But unfortunately I am getting a bad status error. Here is my provider and builder - Provider -

class RegistrationSendCode extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return BlocProvider<RegistrationSendCodeCubit>(
      create: (context) => RegistrationSendCodeCubit(),
      child: RegistrationSendCodeBuilder(),
    );
  }
}

Builder -

class RegistrationSendCodeBuilder extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RegistrationSendCodeCubit, RegistrationSendCodeState>(
      builder: (context, state) {
        if(state is RegistrationSendCodeNotLoading) {
          RegistrationSendCodeWidget();
        } else if(state is RegistrationSendCodeLoading) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator(),),
          );
        } else if(state is RegistrationSendCodeLoaded) {
          return FullName();
        } else if(state is RegistrationSendCodeError) {
          return MyError();
        }
        throw StateError('err');
      },
    );
  }
}

error -

The following StateError was thrown building BlocBuilder<RegistrationSendCodeCubit, RegistrationSendCodeState>(dirty, dependencies: [_InheritedProviderScope<RegistrationSendCodeCubit?>], state: _BlocBuilderBaseState<RegistrationSendCodeCubit, RegistrationSendCodeState>#cd448):
Bad state: err

The relevant error-causing widget was: 
  BlocBuilder<RegistrationSendCodeCubit, RegistrationSendCodeState> BlocBuilder: return BlocProvider<RegistrationSendCodeCubit>(

It is expected that when I go to this screen, I should immediately get into the RegistrationSendCodeNotLoading state, which is logical


Solution

  • You are throwing the error, But you are not catching it anywhere

    Try removing the line.

    class RegistrationSendCodeBuilder extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
        return BlocBuilder<RegistrationSendCodeCubit, RegistrationSendCodeState>(
          builder: (context, state) {
            if(state is RegistrationSendCodeNotLoading) {
               return RegistrationSendCodeWidget();  👈 add return 
            } else if(state is RegistrationSendCodeLoading) {
              return const Scaffold(
                body: Center(child: CircularProgressIndicator(),),
              );
            } else if(state is RegistrationSendCodeLoaded) {
              return FullName();
            } else if(state is RegistrationSendCodeError) {
              return MyError();
            }
            throw StateError('err');  // ❌ remove this line
          },
        );
      }
    }