5

I'm using flutter_bloc and I need a bloc to communicate with another bloc - I have an activityBloc that needs to listen to the authBloc to determine if the author is authenticated and get the userid ( the intention is to start listening to document changes on firestore based on the userid from authentication).

I'm passing in the dependant object to the activityBloc via the constructor.

class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
  final AuthBloc authBloc;
  final ActivityRepository repo;
  StreamSubscription authSubscription;
  StreamSubscription activitySubscription;
  String id; // userid
  int limit = 10;

  ActivityBloc({this.authBloc, this.repo}) {
    id = "";

    authSubscription = authBloc.listen((state) {
      if (state is AuthenticatedState) {
        id = state.user.uid;
        ...
          });
        });
      }
    });
  }

  @override
  ActivityState get initialState => ActivityInitial();
...
}

I need to have these exposed within the a multibloc provider, how would I be able to instantiate the blocs within the mulitbloc provider where one bloc needs to be passed into another bloc ?

Thanks

user3836415
  • 952
  • 1
  • 10
  • 25

2 Answers2

9

You can use the instance of one bloc into another bloc by following.

return MultiBlocProvider(
  providers: [
    BlocProvider<AuthBloc>(
      create: (BuildContext context) => AuthBloc(),
    ),
    BlocProvider<ActivityBloc>(
      create: (BuildContext context) => ActivityBloc(
        authBloc: BlocProvider.of<AuthBloc>(context),
        repo: /// instance of your activity repository,
      ),
    ),
  ],
  child: App(),
);
Chinmay Mourya
  • 764
  • 5
  • 9
-2

Hi I'm not sure if it possible with flutter_bloc library but you can use awesome provider library https://pub.dev/packages/provider#-installing-tab- it's approved by Google (not only for bloc)

Also, flutter_bloc is using Provider too

There is ProxyProvider, I'm not sure what privileges give you flutter_bloc library because everything you need you can do without it, as for me I'm using just provider library

Here is code that will solve your problem, for more info how to work with provider check out https://pub.dev/packages/provider

MultiProvider(
  providers: [
    Provider<AuthBloc>(
      create: (_) => AuthBloc(),
      dispose: (_, bloc) => bloc.dispose(),
    ),
    ProxyProvider<AuthBloc,ActivityBloc>(
    create: (_) => ActivityBloc(),
    update: (_, authBloc, bloc) => bloc..authBloc = authBloc, //insert authBloc to ActivityBloc
    dispose: (_, bloc) => bloc.dispose(),
    ),
  )
  ],
  child: App(),
)

and then acces any of provider inside App widget

@override Widget build(BuildContext context) {
final bloc = Provider.of<ActivityBloc>(context);
Philip Dolenko
  • 618
  • 1
  • 6
  • 12