Flutter eventbus 官方文檔 記錄
class EventBus {
// 私有構(gòu)造器
EventBus._internal();
static EventBus _instance;
static EventBus get instance => _getInstance();
// 工廠模式
factory EventBus() => _getInstance();
// 構(gòu)建單例
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);
}
}
// 發(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);
}
}
}