参考文档:电梯直达
EventBusUtils
//订阅者回调签名
typedef void EventCallback(arg);
///* 作者:guoyzh
///* 时间:2020年1月7日
///* 功能:创建eventBus工具类
class EventBus {
/// 私有构造函数
EventBus._internal();
/// 保存单例
static EventBus _singleton = new EventBus._internal();
/// 工厂构造函数
factory EventBus() => _singleton;
/// 保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
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 send(eventName, [arg]) {
var list = _eMap[eventName];
if (list == null) return;
int len = list.length - 1;
//反向遍历,防止订阅者在回调中移除自身带来的下标错位
for (var i = len; i > -1; --i) {
list[i](arg);
}
}
}
订阅事件
class RefundPage extends StatefulWidget {
RefundPage({this.title, this.name});
final String title;
final String name;
@override
_RefundPageState createState() => _RefundPageState();
}
class _RefundPageState extends State<RefundPage> {
/// 获取全局单例的EventBus
var bus = EventBus();
// props 从 widget.xxx 获取
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(title: widget.title, isShowBack: true),
body: Column(children: <Widget>[
GestureDetector(
onTap: () {
bus.send("flush", "退款界面的数据");
},
child: ListTile(title: Text("商品列表"))),
Expanded(
child:
ListView.builder(itemBuilder: (BuildContext context, int index) {
return ListTile(title: Text(""));
}),
),
]),
);
}
/// 取消订阅事件
@override
void dispose() {
super.dispose();
bus.off("flush");
}
}
界面关闭取消订阅(防止内存泄漏)
/// 取消订阅事件
@override
void dispose() {
super.dispose();
bus.off("flush");
}
发送事件
var bus = EventBus();
@override
void deactivate() {
super.deactivate();
/// 必须在deactivate方法中声明 才可以保证事件不会因为bus移除事件而无法推送
bus.on("flush", (arg) {
AppUtils.showToast(arg);
});
}