Reputation: 13
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: blocProviders(context),
child: MaterialApp.router(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
routerConfig: AppRouter().router,
),
);
}
}
// this is a another file what i assigned BlocProvider this way
List<BlocProvider> blocProviders (context){
return [
BlocProvider(create: (_) => BottomMenuCubit()),
BlocProvider(create: (_) => CounterCubit())
];
}
can any body tell me what is the issuse here . Actually i defined providers into another file in form list funcation which is return a list of blocProviders. but I got this error
Error: Could not find the correct Provider<BottomMenuCubit> above this BlocBuilder<BottomMenuCubit, BottomMenuState> Widget
This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:
If i assign directly it's fine . But i want to solve this way
Upvotes: 1
Views: 42
Reputation: 2541
Here:
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: blocProviders(context)...
you are using context from build method. This contex know nothing about you MultiBlocProvider
.
Easiest way is to wrap MultiBlocProvider
in Builder
.
Or extract MultiBlocProvider
in sepatate widget:
class RootDependenciesProvider extends StatelessWidget {
const RootDependenciesProvider({
required this.app,
super.key,
});
final WidgetBuilder app;
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<BottomMenuCubit>(create: (_) => BottomMenuCubit()),
BlocProvider<CounterCubit>(create: (_) => CounterCubit()),
],
child: app(context),
);
}
}
Upvotes: 0
Reputation: 895
It seems BlocProvider
didn't get the correct Bloc
type. I don't know exactly why it happens, but you can solve this issue by assigning Bloc type explicitly.
List<BlocProvider> blocProviders (context){
return [
BlocProvider<BottomMenuCubit>(create: (_) => BottomMenuCubit()),
BlocProvider<CounterCubit>(create: (_) => CounterCubit()),
];
}
Upvotes: 0