1.首先导入使用EventBus时所需的包:event_bus: ^1.1.1
2.还需要一个EventBus工具类:
import 'dart:async';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/widgets.dart';
/// EventBus的工具类
class HosEventBusUtils {
// 单列模式
static EventBus _eventBus;
static EventBus shared() {
if (_eventBus == null) {
_eventBus = EventBus(); // 创建事件总线
}
return _eventBus;
}
/// 订阅者
static Map<Type, List<StreamSubscription>> subscriptions = {};
/// 添加监听事件
/// [T] 事件泛型 必须要传
/// [onData] 接受到事件
/// [autoManaged] 自动管理实例,off 取消
static StreamSubscription on<T extends Object>(void onData(T event),
{Function onError,
void onDone(),
bool cancelOnError,
bool autoManaged = true}) {
StreamSubscription subscription = shared()?.on<T>()?.listen(onData,
onError: onError,