简体   繁体   中英

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')
          );
    },
  );
}

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( ...
     ...

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