skip to Main Content
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

2

Answers


  1. 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()),
      ];
    }
    
    Login or Signup to reply.
  2. 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),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search