Create an instance of EventBus and make it available to other classes.
Usually there is just one Event Bus per application, but more than one may be set up to group a specific set of events.
import ‘package:event_bus/event_bus.dart‘;
EventBus eventBus = EventBus();
Note: The default constructor will create an asynchronous event bus. To create a synchronous bus you must provide the optional sync: true attribute.
Any Dart class can be used as an event.
import ‘package:event_bus/event_bus.dart‘;
import ‘package:flutter/material.dart‘;
EventBus eventBus=EventBus();
class AnyEvent{
Widget listWidget;
AnyEvent(Widget listWidget){
this.listWidget=listWidget;
}
}
Register listeners for specific events:
eventBus.on<UserLoggedInEvent>().listen((event) {
// All events are of type UserLoggedInEvent (or subtypes of it).
print(event.user);
});
Register listeners for all events:
eventBus.on().listen((event) {
// Print the runtime type. Such a set up could be used for logging.
print(event.runtimeType);
});
EventBus uses Dart Streams as its underlying mechanism to keep track of listeners. You may use all functionality available by the Stream API. One example is the use of StreamSubscriptions to later unsubscribe from the events.
StreamSubscription loginSubscription = eventBus.on<UserLoggedInEvent>().listen((event) {
print(event.user);
});
loginSubscription.cancel();
Finally, we need to fire an event.
User myUser = User(‘Mickey‘);
eventBus.fire(UserLoggedInEvent(myUser));
Instead of using the default StreamController you can use the following constructor to provide your own.
An example would be to use an RxDart Subject as the controller.
import ‘package:rxdart/rxdart.dart‘;
EventBus behaviorBus = EventBus.customController(BehaviorSubject());
原文:https://www.cnblogs.com/braveheart007/p/10848400.html