50 lines
1.1 KiB
Dart
50 lines
1.1 KiB
Dart
|
|
import 'package:event_bus/event_bus.dart';
|
|||
|
|
|
|||
|
|
// 创建 EventBus 实例(私有)
|
|||
|
|
EventBus _eventBus = EventBus();
|
|||
|
|
|
|||
|
|
/// 全局事件总线工具类(单例)
|
|||
|
|
class EventBusUtil {
|
|||
|
|
// 工厂构造函数,确保返回唯一实例
|
|||
|
|
factory EventBusUtil() => _instance;
|
|||
|
|
|
|||
|
|
// 私有构造函数
|
|||
|
|
EventBusUtil._internal();
|
|||
|
|
|
|||
|
|
// 静态实例
|
|||
|
|
static final EventBusUtil _instance = EventBusUtil._internal();
|
|||
|
|
|
|||
|
|
/// 获取 EventBus 实例
|
|||
|
|
EventBus get instance => _eventBus;
|
|||
|
|
|
|||
|
|
/// 监听指定类型的事件
|
|||
|
|
///
|
|||
|
|
/// 示例:
|
|||
|
|
/// ```dart
|
|||
|
|
/// EventBusUtil().on<UserLoginEvent>((event) {
|
|||
|
|
/// print('用户登录:${event.userId}');
|
|||
|
|
/// });
|
|||
|
|
/// ```
|
|||
|
|
Stream<T> on<T>() {
|
|||
|
|
return _eventBus.on<T>();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 发送事件
|
|||
|
|
///
|
|||
|
|
/// 示例:
|
|||
|
|
/// ```dart
|
|||
|
|
/// EventBusUtil().fire(UserLoginEvent('123'));
|
|||
|
|
/// ```
|
|||
|
|
void fire<T>(T event) {
|
|||
|
|
_eventBus.fire(event);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 销毁 EventBus(一般不用调用,除非应用退出)
|
|||
|
|
void destroy() {
|
|||
|
|
_eventBus.destroy();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 快捷访问方式(可选)
|
|||
|
|
EventBusUtil $eventBus = EventBusUtil();
|