#事件監(jiān)聽
event_bus: ^1.1.1
事件代碼
import 'package:event_bus/event_bus.dart';
class TestEventBus {
static final TestEventBus _gInstance = TestEventBus._init();
EventBus _eventBus = EventBus();
TestEventBus._init() {
///
}
factory TestEventBus() {
return _gInstance;
}
EventBus get bus {
return _eventBus;
}
}
使用:
創(chuàng)建事件
class ProgressEvents {
String data;///傳輸數(shù)據(jù)就在這里加
ProgressEvents({this.data});
}
觸發(fā)的地方:
ProgressEventBus().bus.fire(ProgressEvents(data: ''));
監(jiān)聽的地方:
ProgressEventBus().bus.on<ProgressEvents>().listen((event) {
if (!mounted) return;
});
///取消訂閱
StreamSubscription subscription;
subscription=ProgressEventBus().bus.on<ProgressEvents>().listen((event) {
if (!mounted) return;
});
@override
void dispose() {
// TODO: implement dispose
super.dispose();
if (subscription != null) {
subscription.cancel();
}
}
注:監(jiān)聽應比觸發(fā)早。