flutterevent_bus使⽤介绍(重要)
创建消息对象
class UrLoggedInEvent {
Ur ur;
UrLoggedInEvent(this.ur);
}
创建eventBus
EventBus eventBus = EventBus();
注册订阅这⾥可以将保存下来 dispo可以将该stream移除订阅
StreamSubscription loginSubscription = <UrLoggedInEvent>().listen((event) {
// All events are of type UrLoggedInEvent (or subtypes of it).
print(event.ur);
});
<<UrLoggedInEvent>().listen((event) {
// All events are of type UrLoggedInEvent (or subtypes of it).
print(event.ur);
});
发送消息
Ur ur = {};
eventBus.fire(UrLoggedInEvent(ur));
移除eventBus
@override
魏元忠void dispo() {
loginSubscription.cancel();
super.dispo();
}
主要注意的是添加过订阅后⼀定要将订阅steam移除,否则,页⾯计算被移除,仍然可以接收到订阅消息,造成内存泄漏基于官⽅给的使⽤⽅法,对eventbus做了⼀层封装,⽅便在项⽬中使⽤
import 'dart:async';
import 'package:event_bus/event_bus.dart';
typedef void EventCallback<T>(T event);
class EventBusUtils {
factory EventBusUtils() => _getInstance();
static EventBusUtils get instance => _getInstance();
static EventBusUtils _instance;
EventBusUtils._internal() {
// 初始化
_eventBus = new EventBus();
}
//初始化eventBus儿童科技小制作
EventBus _eventBus;
// EventBus get eventBus => _eventBus;
/// 订阅stream列表
// List<StreamSubscription> subscriptionList;
static EventBusUtils _getInstance() {
if (_instance == null) {
_instance = new EventBusUtils._internal();
}
return _instance;
}
/// 开启eventbus订阅并
123的英文StreamSubscription on<T>(EventCallback<T> callback) {
StreamSubscription stream = _<T>().listen((event) {
浇花callback(event);
});
// subscriptionList.add(stream);
return stream;
}
/// 发送消息
void emit(event) {
_eventBus.fire(event);
}
/// 移除steam
void off(StreamSubscription steam) {
steam.cancel();
外面的英文}
}
var eventBus = EventBusUtils.instance;
使⽤起来很很简单
var loginSuccessEvent;
添加订阅
loginSuccessEvent = <UrLoggedInEvent>((event) {
print('page A received msg');
tState(() {
params = event.urInfo;
});
});
发送消息订阅经折装
Ur ur = {};
取消订阅
@override
void dispo() {
eventBus.off(loginSuccessEvent);抑亢丸
super.dispo();
}怎样炖排骨
封装之后,使⽤变的简化了
需要注意⼀点的是在使⽤event_bus的时候不要调⽤destroy()⽅法,否则将⽆法收到消息监听,如果要移除订阅,请使⽤ stream.cancel();