Flutter could not find the correct Provider above BlocConsumer Widget

Issue

I’m using Flutter Bloc for a project.

This is the structure:

      MultiBlocProvider(
          providers: [
            BlocProvider<BlocA>(
              create: (context) {
                return BlocA()
                  ..add(FetchEvent());
              },
            ),
            BlocProvider<BlocC>(
              create: (context) {
                return BlocC()..add(FetchEvent());
              },
            ),
          ],
          child: IndexedStack(
            index: _pageNum,
            children: [
              ChildA(),
              ChildB(),
            ],
          ),
        )

Inside ChildB I have a Navigator.push() to a ChildC, where BlocC is being used (BlocConsumer), but I’m getting an error,

Flutter could not find the correct Provider above BlocConsumer<BlocC> Widget

Edit
There is a button in ChildB that navigates to ChildC on pressed.
Like,

TextButton( // this code exists inside a scaffold widget
   child: Text("Page C"),
   onPressed: () {
      Navigator.push(context, CupertinoPageRoute(builder: (context) => ChildC()));
   }
), 

This is the bloc consumer in ChildC

// Child C
 Scaffold(
      body: BlocConsumer<BlocC, CState>(
        builder: (context, state) {
          if(state is CSuccessState) {
            return _body();
          } else if (state is CLoadingState || state is CInitState) {
            return Center(child: CircularProgressIndicator());
          } else return Center(child: Text("Something went wrong"));
        },
        listener: (context, state) {},

      ),
    );

Edit 2

I found this answer, apparently, this is an issue when using Navigator.push. Still, if anyone knows how to solve it in my case, do let me know

Solution

The Navigator’s behaviour is expected.

You should replace
Navigator.push(context, CupertinoPageRoute(builder: (context) => ChildC()));
with

Navigator.push(context, CupertinoPageRoute(builder: (ctx) => BlocProvider.value(value: context.read<BlocC>()), child: ChildC());

This will work.

Answered By – Rahul Sharma

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.