Abdi mussa
Abdi mussa

Reputation: 253

How to pass a bloc to another screen using go_router on flutter

On Flutter I would like to pass a local bloc to another screen. This is how I used to pass a bloc to a new route when using the default navigator.

Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) =>  BlocProvider.value(
          value: localBloc,
          child: MyPage(),
      ),
    ));

But now, I'm using the go_router package for navigation. How can I provide the local bloc to the screen I want using BlocProvider.value().

Upvotes: 13

Views: 7047

Answers (2)

Ilia Zadiabin
Ilia Zadiabin

Reputation: 209

You need to pass the bloc to the route using BlocProvider.value.

context.goNamed('/', extra: HomeBloc());

GoRoute(
  path: '/',
  builder: (context, state) { 
    return BlocProvider.value(
      value: state.extra! as HomeBloc,
      child: HomeScreen(),
    );
  }
),

And then inside HomeScreen you can get bloc using.

final bloc = context.read<HomeBloc>();

Upvotes: 13

krishnaacharyaa
krishnaacharyaa

Reputation: 25120

BlocProviders are lazy loaded by default.

It automatically handles closing the instance when used with Create. By default, Create is called only when the instance is accessed. To override this behavior, set lazy to false.

Therfore instead of passing bloc between routes,The best practice is to:

Provide all the BlocProvider in the main.dart using the MultiBlocProvider

And add it before App() so that all the child can get access to it .

  runApp(
      MultiBlocProvider(
          providers: [
            BlocProvider<BlocA>(
              create: (context) => BlocA(),
            ),
             BlocProvider<BlocB>(
              lazy: false                   // if you want the bloc to be loaded here.
              create: (context) => BlocB(),
            ),

          ],
          child: App()
      )
  );

And access it using BlocProvider.of<BlocA>(context).add([BlocAEvent]); in your desired screen

Upvotes: -4

Related Questions