简体   繁体   中英

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

@override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
    providers: [
         BlocProvider<TripDetailBloc>(create: (BuildContext context) => TripDetailBloc()),
         BlocProvider<PopUpBloc>(create: (BuildContext context) => PopUpBloc()),
               ],
    child: Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          BlocProvider.of<TripDetailBloc>(context).add(AddTripDetailPannelEvent());
        },
      ),
      appBar: appbar(),
      body: pannel(),
    )
    );
  }

The following assertion was thrown while handling a gesture:

  • BlocProvider.of() called with a context that does not contain a Bloc of type TripDetailBloc.
  • No ancestor could be found starting from the context that was passed to BlocProvider.of <TripDetailBloc>() .
  • This can happen if the context you used comes from a widget above the BlocProvider.
  • he context used was: TripDetailPage(dependencies: [MediaQuery], state: _TripDetailPageState#d4ab3)

Change your code to this:

Widget build(BuildContext context) {
  
  return MultiBlocProvider(
      providers: [
        BlocProvider<TripDetailBloc>(create: (BuildContext context) => TripDetailBloc()),
        BlocProvider<PopUpBloc>(create: (BuildContext context) => PopUpBloc()),
      ],
      child: Builder(
        builder: (context) {
          return Scaffold(
            floatingActionButton: FloatingActionButton(
              child: Icon(Icons.add),
              onPressed: () {
                BlocProvider.of<TripDetailBloc>(context).add(AddTripDetailPannelEvent());
              },
            ),
            appBar: appbar(),
            body: pannel(),
          );
        }
      )
  );
}

If you look closely, I have rapped your Scaffold into a widget builder.

Wrap your scaffold in a builder widget and use that context. The context the.of(context) is using is the same of the method build(BuildContext context), that's why it doesn't find it

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