skip to Main Content

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.

2

Answers


  1. 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()
        )
      }
    }
    
    Login or Signup to reply.
  2. Try passing the type like so

    BlocBuilder<BlocA, BlocAState>(
      builder: (context, state) {
      // return widget here based on BlocA's state
      }
    )
    

    Example for your case, if you want the LoginCubit pass the cubit & state after the BlockBuilder between the angle brackets <>.

    
    // this
     child: BlocBuilder(builder: (context, state) {
              return Scaffold(
    
    // should look like this
     child: BlocBuilder<LoginCubit, LoginState>(builder: (context, state) {
              return Scaffold(
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search