Skip to Content
Event ModuleModularEventMixin

ModularEventMixin

ModularEventMixin lets a widget react to typed events tied to its own lifecycle. Register listeners in initState and the mixin cancels all of them automatically in dispose() — no manual cleanup.

Usage

Apply the mixin to a State and register listeners with on:

lib/src/widgets/cart_badge.dart
class CartBadge extends StatefulWidget { const CartBadge({super.key}); @override State<CartBadge> createState() => _CartBadgeState(); } class _CartBadgeState extends State<CartBadge> with ModularEventMixin { int _count = 0; @override void initState() { super.initState(); on<ProductAdded>((event, context) { setState(() => _count++); }); } @override Widget build(BuildContext context) => Text('$_count'); }

Fire events to it from anywhere:

ModularEvent.fire<ProductAdded>(ProductAdded(product));

Registering listeners

on<E>( void Function(E event, BuildContext? context) callback, { EventBus? eventBus, bool exclusive = false, });
  • context is mounted ? context : null — always null-check before using it.
  • Registering on<E> twice for the same type replaces the previous listener.
  • eventBus: omit to use the global defaultModularEventBus; pass a custom EventBus to isolate this widget’s listeners.
  • exclusive: when true, uses a broadcast stream for the type.

All subscriptions registered through the mixin are cancelled automatically in the widget’s dispose(). You never cancel them yourself.

Choosing an approach

ApproachScopeCleanup
EventModuleModule-scoped business reactionsTied to module lifecycle
ModularEventMixinWidget-scoped UI reactionsTied to widget lifecycle
ModularEvent.instanceGlobalManual

Next steps

Last updated on