如何在flutter中自己实现事件总线(EventBus)
// 福利中心组件部分,事件总线,方便业务更新数据
typedef EventCallback = void Function(dynamic arg);
//消息类型
class RewardsNotify {
  //消息类型
  static const takeChance = 'takeChance'; //首页抽奖次数
}
class RewardsEventBus {
  //工厂构造函数
  factory RewardsEventBus() => _singleton;
  //私有构造函数
  RewardsEventBus._internal();
  //保存单例
  static final RewardsEventBus _singleton = RewardsEventBus._internal();
  //保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
  final _eMap = <Object, List<EventCallback>?>{};
  //添加订阅者
  void on(final String eventName, final EventCallback f) {
    _eMap[eventName] ??= <EventCallback>[];
    _eMap[eventName]!.add(f);
  }
  //移除订阅者
  void off(final String eventName, [final EventCallback? f]) {
    final list = _eMap[eventName];
    if (list == null) {
      return;
    }
    if (f == null) {
      _eMap[eventName] = null;
    } else {
      list.remove(f);
    }
  }
  //触发事件,事件触发后该事件所有订阅者会被调用
  void emit(String eventName, [dynamic arg]) {
    final list = _eMap[eventName];
    if (list == null) {
      return;
    }
    final len = list.length - 1;
    //反向遍历,防止订阅者在回调中移除自身带来的下标错位
    for (var i = len; i > -1; --i) {
      list[i](arg);
    }
  }
}
RewardsEventBus rewardsBus = RewardsEventBus();
文章目录
                            关闭
                        
共有 0 条评论