Message: Could not find the correct Provider above this Home Widget
This happens because you used a BuildContext
that does not include the provider
of your choice.
Here’s the blocProvider and blocBuilder set up you can get the jest of it I’m sure.
Widget build(BuildContext context) {
return Scaffold(
body: BlocProvider<PageRoutingCubit>(
create: (context) => PageRoutingCubit(),
child: BlocBuilder<PageRoutingCubit, PageRoutingStates>(
builder: (context, state) {
if (state is PageRoutingProfileState) {
return ProfileScreen();
} else if (state is PageRoutingSettingsState) {
return SettingsScreen();
} else if (state is PageRoutingCartState) {
return CartScreen();
} else {
return Center(
child: Text('Error'),
);
}
})),
I then added a drawer with button to control the body of the scaffold with said buttons.
```Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
DrawerButton(
onTap: () => context
.read<PageRoutingCubit>()
.BuildProfileScreen(),
text: 'Profile',
icon: Icon(Icons.person)),
DrawerButton(
onTap: () => context
.read<PageRoutingCubit>()
.BuildSettingsScreen(),
text: 'Settings',
icon: Icon(Icons.settings)),
DrawerButton(
onTap: () => context
.read<PageRoutingCubit>()
.BuildCartScreen(),
text: 'Cart',
icon: Icon(Icons.shopping_cart)),
],
),```
It keeps telling me to add a builder but I already supplied it with the builder it wants.
Please help me quickly and thank you.
2
Answers
I see, in that case, it’s possible that the
BuildContext
that you are using to call thecontext.read<PageRoutingCubit>()
method is not a descendant of theBlocProvider
widget.Make sure that the
BuildContext
you are using is coming from a widget that is a descendant of theBlocProvider
widget. You can do this by either moving theBlocProvider
higher up in the widget tree or by using aBuilder
widget to create a newBuildContext
that is a descendant of theBlocProvider
.Here’s an example using the
Builder
widget:In this example, the
Builder
widget creates a newBuildContext
that is a descendant of theBlocProvider
widget, and we use thisBuildContext
to call thecontext.read<PageRoutingCubit>()
method.I hope this helps! Let me know if you have any further questions.
Wrap the Scaffold with a
BlocProvider
AND wrap the Drawer with a regularBuilder
widget so that you use the context with the bloc added to it. If you don’t want the "hack" with a Builder wrapping the Drawer, you could extract the drawer widget to its own widget and you will be able to access the bloc inside the passed down context.