SoFunction
Updated on 2025-03-11

Detailed explanation of the application of Flutter EventBus event bus

Preface

In the flutter project, there are many solutions that can implement cross-component communication, including InheritedWidget, Notification, EventBus, etc. This article mainly discusses the method of the EventBus event bus to realize cross-component communication.

Introduction to EventBus

EventBusThe core ofStreams. It allows listeners to subscribe to events and allows publishers to trigger events, so that data from different components does not need to be passed layer by layer, and can be directly passedEventBusImplement cross-component communication.

EventBusThe most important thing is throughTrigger eventandListen to eventsTwo operations are used to achieve cross-layer access to different pages. The triggering event is performed through the fire(event) method, and the listening event is performed through the on<T>() method, where generics can be passed into the specified type, and the event bus will be listened to in a targeted manner. If the generic pass value is empty, all types of events are listened to by default:

void fire(event) {
  (event);
}
Stream<T> on<T>() {
  if (T == dynamic) {
    return  as Stream<T>;
  } else {
    return ((event) => event is T).cast<T>();
  }
}

Actual application of EventBus

1. InReference eventBus event bus dependencies in the file;

2. Create a globalEventBusExamples;

3. Usefire(event)Method triggers a new event on the event bus (trigger event);

4. Register a listener (listen to events) for the event bus;

5. Cancel the EventBus event subscription to prevent memory leakage.

// 1. Reference eventBus event bus dependency in the file;dependencies:
    event_bus: ^2.0.0
// 2. Create a global EventBus instance;EventBus myEventBus = EventBus();
// 3. Use the fire(event) method to trigger a new event (trigger event) on the event bus;Center(
  child: ElevatedButton(
    onPressed: () {
      ('Triggering event through EventBus');
    },
    child: Text('Trigger event'),
  ),
)
var getData;
@override
void initState() {
  // TODO: implement initState
  ();
  // 4. Register a listener (listen to events) for the event bus;  getData = ().listen((event) {
    print(event);
  });
}
@override
void dispose() {
  // TODO: implement dispose
  ();
  // 5. Cancel the EventBus event subscription to prevent memory leakage.  ();
}

Summarize

EventBusIt follows the publish/subscribe mode, which can effectively realize the cross-component communication function through event triggering and listening operations.

The above is the detailed explanation of the application of Flutter EventBus event bus. For more information about Flutter EventBus event bus, please pay attention to my other related articles!