Flutter eventbus 官方文档 记录
class EventBus {
// 私有构造器
EventBus._internal();
static EventBus _instance;
static EventBus get instance => _getInstance();
// 工厂模式
factory EventBus() => _getInstance();
// 构建单例
static EventBus _getInstance() {
if (null == _instance) {
_instance = new EventBus._internal();
}
return _instance;
}
// 保存订阅者事件队列
var _emap = new Map<Object, List<EventCallBack>>();
// 添加订阅者
void on(eventName, EventCallBack f) {
if (eventName == null || f == null) {
return;
}
_emap[eventName] ??= new List<EventCallBack>();
_emap[eventName].add(f);
}
// 移除订阅者
void off(eventName, [EventCallBack f]) {
var list = _emap[eventName];
if (eventName == null || list == null) {
return;
}
if (f == null) {
_emap[eventName] = null;
} else {
list.remove(f);
}
}
// 发射事件 也有可能事件为空
void emit(evenName, [arg]) {
var list = _emap[evenName];
if (list == null) {
return;
}
// 开始通知订阅者
var len = list.length - 1;
for (int i = len; i > -1; --i) {
list[i](arg);
}
}
}