When managing state in Flutter with flutter_bloc
, BLoCs should not have direct dependencies on each other. Instead, we can use the Mediator pattern provided by the flutter_bloc_mediator communication between BLoCs, making the architecture more modular and scalable.
The flutter_bloc_mediator
package introduces a central BlocHub
where all BLoCs register themselves using unique names. Once registered, a BLoC can send messages to another by simply calling methods like sendTo
or sendToAll
. For example, rather than accessing another BLoC’s state directly:
// Avoid this:
final state = BlocProvider.of<BlocA>(context).state;
You can do this:
counterBlocA.sendTo(CounterComType(2), 'CounterB');
Here, CounterComType
is a custom message type that carries the data, and 'CounterB'
is the identifier for the target BLoC. The receiving BLoC then implements a receive
method to handle the incoming messages:
@override
void receive(String from, CommunicationType data) {
if (data is CounterComType) {
counter += data.value;
add(IncrementEvent(count: counter));
print('$name received increment event from $from: Counter = $counter');
}
}
BLoCs communicate through a central hub without holding direct references to one another. This decoupling makes your codebase more modular and easier to maintain.
Centralizing communication in a BlocHub
simplifies tracking and managing inter-BLoC interactions, reducing the complexity that comes with directly coupling state between multiple BLoCs.
Isolated BLoCs mean you can test each component in isolation. You don't need to mock or set up the entire state chain, as each BLoC handles its own messages via the mediator.
As your application grows, this pattern helps keep your state management organized. Adding new features or BLoCs becomes less error-prone since you’re not introducing additional direct dependencies.
By adopting the flutter_bloc_mediator package, you effectively delegate message passing between BLoCs, leading to a more maintainable, testable, and scalable Flutter application. This approach is particularly useful in larger applications where managing state across many components can quickly become unwieldy.