Skip to content

<EventListener>

Overview

The <EventListener> component creates a stateful widget that listens for application-wide events and rebuilds its children when those events occur. It provides a publish-subscribe pattern for decoupled component communication — when an event fires anywhere in your app, all registered listeners are notified and rebuild their UI.

Lifecycle:

  1. Register: The listener registers for the specified event type on initialization
  2. Render: The widget renders its children normally
  3. Notify: When the event fires anywhere in the app, the listener is notified
  4. Handle: If onEvent callback is specified, it's called with the event and payload
  5. Rebuild: The widget rebuilds, allowing children to access updated dependencies
  6. Cleanup: The listener is automatically unregistered when the widget is disposed

Attributes

Name Type Description Required Default
event Enum The event type to listen for. Must be a registered event enum value. Yes -
onEvent Function Optional callback function executed when the event fires. Signature: (Enum event, dynamic payload) => void No null
key Key Widget key for controlling widget identity No null
for String The name of the parent's attribute that will be assigned this component No null
visible bool Controls widget visibility No true

Examples

Rebuild on an Event

A controller with the EventNotifier mixin updates dependencies and posts the event; the listener rebuilds and its children read the fresh values:

cart_controller.dart
class CartController extends Controller with EventNotifier<AppEvent> {
  final _items = <Item>[];

  void addItem(Item item) {
    _items.add(item);
    dependencies.setValue("cartCount", _items.length);
    postEvent(AppEvent.cartUpdated, _items.length);
  }
}
XML
<EventListener event="AppEvent.cartUpdated">
    <Text data="Cart: ${cartCount} items"/>
</EventListener>

Handling the Event Payload

Bind onEvent to run a handler before the rebuild — it receives the event and its payload:

// bound in the controller: dependencies.setValue("onCartEvent", onCartEvent);
void onCartEvent(Enum event, dynamic payload) {
  dependencies.setValue("lastCartChange", DateTime.now());
}
XML
<EventListener event="AppEvent.cartUpdated" onEvent="${onCartEvent}">
    <Text data="Cart: ${cartCount} items"/>
</EventListener>

See Events for registering event enums and the full posting/listening API.

See Also