Dispatch your bloc
events
globally instead of having to target specific bloc
s.
About
bloc_chain
allows you to dispatch events globally to all your 'Chained
' Bloc
s.
This means you no longer have to add events to specific Bloc
s like before with:
context.read<MyBloc>().add(MyEvent());
This is specially usefull when a user action has impact on multiple blocs.
For example, when a user logs out from your todo application, you might want to:
- Clear user profile
- Clear user todos
- Clear user settings
With bloc_chain
you don't have to call each Bloc
indifidually like:
ElevatedButton(
child: Text('logout'),
onTap: () {
context.read<ProfileBloc>().add(Logout());
context.read<TodosBloc>().add(ClearTodos();
context.read<SettingsBloc>().add(Clear());
}
)
Instead you just dispatch a single user event:
ElevatedButton(
child: Text('logout'),
onTap: () => BlocChain.add(Logout()),
)
Updating your Blocs
If you want to use bloc_chain
for your existing application that uses the bloc
package, all you have to do is make your bloc
s extend ChainedBloc
instead of Bloc
.
Bloc
class MyBloc extends Bloc<MyEvent, MyState> {
const MyBloc() : super(MyInitialState);
}
ChainedBloc
class MyBloc extends ChainedBloc<MyState> {
const MyBloc() : super(MyInitialState);
}
Notice that you no longer need to specify an event type
.
This is because all the events should inherit from GlobalEvent
.
So you need to update your existing events like so:
Old
abstract class MyEvent {
const MyEvent();
}
New
abstract class MyEvent extends GlobalEvent {
const MyEvent();
}
NOTE: When your event was already extending Equatable, you can use
EquatableMixin
instead.
Dispatching events
Now instead of calling add()
on each specific Bloc
you should use BlocChain.add()
.
Bloc
context.read<MyBloc>().add(MyEvent());
ChainedBloc
BlocChain.instance.add(MyEvent());
Additional information
As you can see, the BlocChain.add
function is currently static.
I might change this in the future, but I really like the simplicity of usage that this gives me.
Libraries
- bloc_chain
- Global event dispatcher for
bloc
.