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());

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:

  1. Clear user profile
  2. Clear user todos
  3. 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 blocs 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.