Bloc: [Discussion : Can we use Bloc as a singleton so it is easy to share across blocs]

Created on 8 Sep 2019  路  2Comments  路  Source: felangel/bloc

  1. Why can't we implement BLoC as a singleton so it can be accessed from everywhere in the app. Sometimes I found BLoC provider is a bit awkward when navigating to a new page.

  2. Also, I want to know what is the proper way to solve cyclic reference. For example, blocA wants to send event to blocB and blocB wants to send to blocA as well. In such situation, do we have a general design for solving all these ?

Thanks so much, I'd be happy if there were already discussion about this : )

question

Most helpful comment

Hi @imaffe 馃憢
Thanks for opening an issue!

As @bigworld12 pointed out you can use BlocProvider to provide a global instance of a bloc by providing the bloc above MaterialApp.

BlocProvider(
  builder: (context) => MyGlobalBloc(),
  child: MaterialApp(...),
)

Regarding circular dependencies, in general you want to avoid them. If you provide additional information around why you need a circular dependency between two blocs I'd be more than happy to suggest alternative approaches 馃憤

Hope that helps and thanks @bigworld12!

All 2 comments

  1. you can implement it as a singleton using bloc provider, just place it as a parent to MaterialApp widget
    but it's actually better than a singleton, since it handles disposal and initialization

  2. bloc A can dispatch an event to bloc B (carrying whatever data you want) , and bloc B can dispatch an event to bloc A (carrying whatever data you want)

Hi @imaffe 馃憢
Thanks for opening an issue!

As @bigworld12 pointed out you can use BlocProvider to provide a global instance of a bloc by providing the bloc above MaterialApp.

BlocProvider(
  builder: (context) => MyGlobalBloc(),
  child: MaterialApp(...),
)

Regarding circular dependencies, in general you want to avoid them. If you provide additional information around why you need a circular dependency between two blocs I'd be more than happy to suggest alternative approaches 馃憤

Hope that helps and thanks @bigworld12!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timtraversy picture timtraversy  路  3Comments

nerder picture nerder  路  3Comments

ricktotec picture ricktotec  路  3Comments

MahdiPishguy picture MahdiPishguy  路  3Comments

nhwilly picture nhwilly  路  3Comments