EventBus not fire when in abstract base class
Closed this issue · 2 comments
lyquocnam commented
create eventbus:
injector.map<EventBus>((i) => new EventBus(sync: true));
i have base class
like this:
abstract class BaseState<T extends StatefulWidget> extends State<T> {
final _scaffoldKey = new GlobalKey<ScaffoldState>();
final _event = injector.get<EventBus>();
StreamSubscription _sub;
@override
void initState() {
_sub = _event.on<MessageChangedEvent>().listen((event) {
show(event.message);
}, onError: (e) {
print(e);
}, onDone: () {
print('done');
});
super.initState();
}
@override
void dispose() {
// TODO: implement dispose
_sub.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text(title()),
),
body: content(),
);
}
void show(String text) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(text),
));
}
String title();
Widget content();
}
and fire event in child class:
class _State extends BaseState<AboutPage> {
final _event = injector.get<EventBus>();
// @override
// void initState() {
// super.initState();
// _event.on<MessageChangedEvent>().listen((event) {
// show(event.message);
// });
// }
void shout() {
_event.fire(new MessageChangedEvent('about', MessageType.info));
}
@override
Widget content() {
return RaisedButton(onPressed: shout, child: Text('login'));
}
@override
String title() {
return 'About';
}
}
please see this case in demo project here:
https://github.com/lyquocnam/flutter-event
ps: if listen event on child class, it's ok.
marcojakob commented
I think it is a problem with dependency injection. You might get two separate instances of EventBus
from the injector (one for _BaseState
and one for _State
). Make sure that there is only one EventBus
.
lyquocnam commented
@marcojakob you are right, the problem is injector, it work fine in normal.
thanks for help author