1.eventBus类
import 'package:event_bus/event_bus.dart';
///event bus
class EventBusUtils {
static EventBus? _eventBus;
static EventBus? getInstance() {
_eventBus ??= EventBus();
return _eventBus;
}
}
2.在接受通知的界面:
//声明,后面需要销毁
StreamSubscription? event;
@override
void initState() {
// TODO: implement initState
super.initState();
//通知监听
event = EventBusUtils.getInstance()?.on().listen((event) {
if(event.toString() == "####"){
//do something here
}
});
}
@override
dispose(){
super.dispose();
//销毁通知,否则可能会注册多个通知,
//不能使用destroy方法,会导致 Cannot add new events after calling close错误
event?.cancel();
}
3.发通知的界面
//发出通知
EventBusUtils.getInstance()?.fire("####");
有被系统的destroy困扰到,只是写了个demo没必要跟我一样,算是给初学者避坑吧
网友评论