bloc_chain 0.0.1 copy "bloc_chain: ^0.0.1" to clipboard
bloc_chain: ^0.0.1 copied to clipboard

Global event dispatching for `bloc`.

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.

3
likes
130
pub points
0%
popularity

Publisher

unverified uploader

Global event dispatching for `bloc`.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (LICENSE)

Dependencies

bloc

More

Packages that depend on bloc_chain