Bloc: BlocProvider.of() called with a context that does not contain a Cubit

Created on 20 Oct 2020  路  3Comments  路  Source: felangel/bloc

Describe the bug
BlocProvider.of() called with a context that does not contain a Cubit

  • I want to add event with BlocProvider.of(context), but I got this error. Help meee!!!!!

image

question

Most helpful comment

Hi @truongduy997 馃憢
Thanks for opening an issue!

Please make sure you are trying to access the bloc from a different BuildContext.

You cannot access it directly from the same context because that BuildContext does not have access to the bloc.

BlocProvider(
  create: (_) => MyBloc(),
  child: TextButton(
    onPressed: () {
      // this will not work because the BuildContext does not have access to the provided bloc
      final bloc = context.bloc<MyBloc>();
    },
  ),
)
BlocProvider(
  create: (_) => MyBloc(),
  child: Builder(
    builder: (context) => TextButton(
      onPressed: () {
        // this will work as expected
        final bloc = context.bloc<MyBloc>();
      },
    ),
  ),
)

Let me know if that helps 馃憤

All 3 comments

BlocProvider.of() will be used to get the existing bloc

// with extensions
context.bloc();

// without extensions
BlocProvider.of(context)

Below method is used to create bloc

BlocProvider(
create: (BuildContext context) => BlocA(),
child: ChildA(),
);

Hi @truongduy997 馃憢
Thanks for opening an issue!

Please make sure you are trying to access the bloc from a different BuildContext.

You cannot access it directly from the same context because that BuildContext does not have access to the bloc.

BlocProvider(
  create: (_) => MyBloc(),
  child: TextButton(
    onPressed: () {
      // this will not work because the BuildContext does not have access to the provided bloc
      final bloc = context.bloc<MyBloc>();
    },
  ),
)
BlocProvider(
  create: (_) => MyBloc(),
  child: Builder(
    builder: (context) => TextButton(
      onPressed: () {
        // this will work as expected
        final bloc = context.bloc<MyBloc>();
      },
    ),
  ),
)

Let me know if that helps 馃憤

Thank @felangel and @venkateshironman so much, i'm done =))
Because i called BlocProvider.of(context) outside BlocBuilder, thank you again for your help !!!!

Was this page helpful?
0 / 5 - 0 ratings