Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modal Bottom Sheet and Bloc

I get the following error when I run code similar to the below code: BlocProvider.of() called with a context that does not contain a Bloc.

To replicate

BlocProvider(
          create: (context) => getIt<TheBloc>()
          child: BlocBuilder<TheBloc, TheState>(
          build: (context, state) =>
          MaterialButton(
            onPressed: () => _showModal(context),
            child: const Text('SHOW BLOC MODAL'),
),

...

void _showModal(BuildContext context) {
  showModalBottomSheet<void>(
    context: context,
    builder: (_) {
          return MaterialButton(
               onPressed() {
                       context.bloc<TheBloc>().add(
                         TheEvent.someEvent(),
                       );
               }
              child: Text('Press button to add event to bloc')
          );
    },
  );
}
like image 513
Gerry Avatar asked Jan 23 '26 20:01

Gerry


1 Answers

You need to wrap the builder of showModalBottomSheet with a BlocProvider.value as follows: As the context is new.

return BlocProvider.value(
     value: BlocProvider.of<TheBloc>(context),
     child: MaterialButton( ...
     ...
like image 85
Gerry Avatar answered Jan 26 '26 10:01

Gerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!