Search code examples
flutterdartbloc

Could not find the correct Provider above this BlocBuilder in MultiBlocProvider


In Flutter I am using bloc and have a special case where is MultiBlocProvider and I need to provide context to widget which is below it.

This is code:

  @override
  Widget build(BuildContext **context**) {
    return MultiBlocProvider(
        providers: [
          BlocProvider<LoginCubit>(create: (_) => LoginCubit()),
          BlocProvider<UserDetailBloc>(
            create: (_) => UserDetailBloc(UserRepository())..add(UserLogged()),
          ),
        ],
        child: BlocBuilder(builder: (context, state) {
          return Scaffold(

Problem is that I am providing the context in bold, what is wrong and it is necessary to provide context below MultiBlocProvider, but I do not know how to declare it in code. There is an example how to do it:

Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builder: (context, child) {
        // No longer throws
        return Text(context.watch<Example>().toString());
      }
    );
  }

But I am not able to find how do declare it with MultiBlocProvider.


Solution

  • Here is the example to use better way MultiBlocProvider

    MultiBlocProvider(
      providers: [
        BlocProvider<BlocA>(
          create: (BuildContext context) => BlocA(),
        ),
        BlocProvider<BlocB>(
          create: (BuildContext context) => BlocB(),
        ),
        BlocProvider<BlocC>(
          create: (BuildContext context) => BlocC(),
        ),
      ],
      child: ChildA(),
    )
    
    class ChildA extends StatelessWidget {
      ChildA({
        super.key,
      });
    
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold()
        )
      }
    }