0 purchases
bloc chain
Dispatch your bloc events globally instead of having to target specific blocs.
About #
bloc_chain allows you to dispatch events globally to all your 'Chained' Blocs.
This means you no longer have to add events to specific Blocs like before with:
context.read<MyBloc>().add(MyEvent());
copied to clipboard
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());
}
)
copied to clipboard
Instead you just dispatch a single user event:
ElevatedButton(
child: Text('logout'),
onTap: () => BlocChain.add(Logout()),
)
copied to clipboard
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 blocs extend ChainedBloc instead of Bloc.
Bloc #
class MyBloc extends Bloc<MyEvent, MyState> {
const MyBloc() : super(MyInitialState);
}
copied to clipboard
ChainedBloc #
class MyBloc extends ChainedBloc<MyState> {
const MyBloc() : super(MyInitialState);
}
copied to clipboard
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();
}
copied to clipboard
New #
abstract class MyEvent extends GlobalEvent {
const MyEvent();
}
copied to clipboard
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());
copied to clipboard
ChainedBloc #
BlocChain.instance.add(MyEvent());
copied to clipboard
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.
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.