flutterflutter-blocflutter-state

Why BlocProvider doesn't allow to assign another list of BlocProvider which I want to import from other file?


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


Solution

  • 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()),
      ];
    }