Home > Enterprise >  Providing BLoCs - Global vs Specific
Providing BLoCs - Global vs Specific

Time:08-09

I am currently learning to use the BLoC pattern for state management and architecture for Flutter and Dart.

I have come across 2 ways of providing access to a BLoC in a widget.

1 - Use BLoCProvider or BLoCProvider.value when accessing a widget and passing it to another screen.

2 - Wrap your MaterialApp widget in a BLoCProvider to provide access to a bloc globally.

It seems that using the 2nd option would always be easiest - a single place to manage your BLoCs, no issues with build context referencing, ensuring a single BLoC instance, and allowing global access!

Are there any drawbacks to creating and providing all an applications BLoCs in this way? Are there any performance issues, etc?

CodePudding user response:

I answered this briefly in another question yesterday.

In short:

  • blocs that need to be globally accessible should of course be. This could e.g. be a bloc that is handling authentication or notifications...
  • other blocs should not be globally accessible, this could e.g. be a bloc that handles fetching information from a backend service etc. I'd love to hear any good reasoning why a screen far down a widget tree that handles something special should have it's bloc globally accessible that any other widget could access...

Having all blocs accessible globally can have a negative effect on performance and it would break common good programming practices.

Edit:

This is from the creator (Felix Angelov) of flutter bloc:

The main disadvantages of providing all blocs globally are:

  • The blocs are never closed so they are consuming resources even if they aren't being used by the current widget tree
  • The blocs can be accessed from anywhere even if the state of the bloc is scoped to just a particular feature
  • The blocs typically end up needing some sort of "reset" event to revert back to the initial state which is not necessary if they are properly scoped and automatically disposed by BlocProvider

My recommendation is to create a bloc per feature and provide that bloc only to the specific subtree that needs it. Hope that helps

  • Related