在 其他前端开发中,为了解耦 会使用事件中心,进行事件的派发; Flutter中 也可以这么操作;
但是呢 插件市场有个叫 event_bus 的;感觉不怎么好用!
所在照着以前的思路;搬了一个!
参考:https://www.jianshu.com/p/d036ed61f1c8 ;但是估计是个老版本的;
这边优化了一下 如下:
typedef void EventCallback(arg); class AppEvent { static final AppEvent _instance = AppEvent._internal(); AppEvent._internal(); factory AppEvent() { return _instance; } //保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列 final _eMap = <dynamic, List<EventCallback>>{}; //添加订阅者 void on(eventName, EventCallback callBack) { if (eventName == null) return; if (!_eMap.containsKey(eventName)) { _eMap.addEntries({eventName: <EventCallback>[]}.entries); } _eMap[eventName]?.add(callBack); } //移除订阅者 void off(eventName, {EventCallback? callBack}) { var list = _eMap[eventName]; if (eventName == null || list == null) return; if (callBack == null) { // _eMap[eventName] = null; _eMap[eventName]?.clear(); } else { list.remove(callBack); } } //触发事件,事件触发后该事件所有订阅者会被调用 void emit(eventName, [arg]) { var list = _eMap[eventName]; if (list == null) { print('**没有找打对应的订阅方法$eventName'); return; } int len = list.length - 1; //反向遍历,防止订阅者在回调中移除自身带来的下标错位 for (var i = len; i > -1; --i) { list[i](arg); } } }
- 添加监听:
AppEvent().on('pageReport-examine', (arg) { print('>>>>>收到消息$arg'); setState(() { _examineListSelect.add(arg); }); });
- 取消监听:
AppEvent().off('pageReport-examine');
- 触发函数:
AppEvent().emit( 'pageReport-examine', { 'id': '110', 'patrolRecordId': 'id', 'routeSubId': 'id', 'placeName': '测试节点', 'checkTime': '', 'isChecked': false, 'checkRecordInfo': { 'trouble': false, 'address': _locationResult?['address'], 'longitude': _locationResult?['latitude'], 'latitude': _locationResult?['longitude'], 'imgs': _selectPicture, 'voicePath': _selectAudio.isNotEmpty ? _selectAudio.first : '', 'bak': '', 'videoPath': _selectVideo.isNotEmpty ? _selectVideo.first : '' }, }, );