How to pass data down the tree using flutter_blocs?

Viewed 253

I am quite stuck on this thing for the past few days.

So my use case here is,  A -> B -> C -> D

Update some data in A when there is some change in D. A, B, C, D are different screens.

Now I understand we can give Two providers to the D using MultiBlocProvide. but I am using the pushed name route,  Not sure how to communicate here using blocs.

routes: {
  Routes.ScreenA: (context) => _getScreenA(),
  Routes.ScreenB: (context) => _getScreenB(),
  Routes.ScreenC: (context) => _getScreenC(),
  Routes.ScreenD: (context) => _getScreenD(),
}

  _getScreenA() {
    return BlocProvider<ScreenABloc>(
        create: (context) =>
            ScreenABloc(),
        child: ScreenARoute());
  }

  _getScreenB() {
    return BlocProvider<ScreenBBloc>(
        create: (context) => ScreenBBloc(),
        child: ScreenBRoute());
  }

  _getScreenC() {
    return BlocProvider<ScreenCBloc>(
        create: (context) => ScreenCBloc(),
        child: ScreenCRoute());
  }

  _getScreenD() {
    return BlocProvider<ScreenDBloc>(
        create: (context) => ScreenDBloc(),
        child: ScreenDRoute());
  }

Also checked the example of Todo's, but now sure how to plug it here.

1 Answers

Rather than wrapping each route with BlocProvider wrap your MaterialApp on your main.dart file with MultiBlocProvider and then initialize all your required bloc classes there, They will be available everywhere on your application. If you are going to way define same bloc over different routes - there will be some data inconsistencies because you are not using same instance of a bloc.

Related