简体   繁体   中英

BlocProvider.of() called with a context that does not contain a RegisterCubit

the error show up when I try to create a new user, registr page worked yesterday and I have not changed anything on it. Can you help me?

Here is my code

register cubit

    class RegisterCubit extends Cubit<RegisterStates> {
      RegisterCubit() : super(RegisterInitialState());
      static RegisterCubit get(context) => BlocProvider.of(context);
      bool isHidePassword = true;
      IconData password = Icons.visibility_outlined;
    
      void changePassword() {
        isHidePassword = !isHidePassword;
        password = isHidePassword
            ? Icons.visibility_outlined
            : Icons.visibility_off_outlined;
        emit(ChangePassVisibility());
      }
    ...

register page

 class Register extends StatelessWidget {
      final formKey = GlobalKey<FormState>();
      final emailController = TextEditingController();
      final passwordController = TextEditingController();
    
  Register({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => RegisterCubit(),
        child: BlocConsumer<RegisterCubit, RegisterStates>(
          listener: (context, state) {},
          builder: (context, state) {
            var cubit = RegisterCubit.get(context);
            return Scaffold(
              ...

BlocProvider must be in a higher BuildContext than the Consumers. Your BlocProvider and BlocConsumer both are in the same context and consumer cannot find the RegisterCubit in that way. You can provide your cubit from root widget of the app. So it will be available for the rest of build contexts. Beside that you can just wrap your BlocConsumer with Builder widget, that will provide a new BuildContext that have access to the your RegisterCubit.

You can try wrapping your MaterialApp "in main.dart" with a MultiBlocProvider then register your bloc provider there

Example:

Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (BuildContext context) => AppCubit(),
        ),
        BlocProvider(
          create: (BuildContext context) => RegisterCubit()
        ),
      ],
      child: BlocConsumer<AppCubit, AppStates>(
          listener: (context, state) {},
          builder: (BuildContext context, state) {
            return MaterialApp(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM