在使用flutter开发过程中有些时候需要在组件之间进行通讯,我们可以借助eventBus来实现。实现步骤如下:
1、导入eventBus第三方包
2、实例化EventBus得到eventBus对象
3、定义事件消息类,一般内部属性为消息实体。
4、在需要订阅消息的组件内部 订阅消息
1、定义观察者
2、在initState函数内部为通过eventBus监听消息其返回值是观察值,eventBus在监听事件时需要明确监听的是哪个消息事 件,需要用到第三步定义的消息类。
3、在dispose函数中销毁观察者。
5、另外一个组件内部通过eventBus来发布消息。
代码如下:
import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';
EventBus eventBus = new EventBus();
class TestScrollNotification extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return TestScrollNotificationState();
}
}
class TestScrollNotificationState extends State<TestScrollNotification> {
Widget render() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[CustomChild1(), CustomChild()], //将子Widget加入到视图树中
);
}
@override
Widget build(BuildContext context) {
return render();
}
}
//抽离出一个子Widget用来发通知
class CustomChild extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
//按钮点击时分发通知
onPressed: () => {eventBus.fire(CustomEvent1('2222222'))},
child: Text("Fire Notification"),
);
}
}
class CustomChild1 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return CustomChild1State();
}
}
class CustomChild1State extends State<CustomChild1> {
String str = "111";
var discrip;
@override
void initState() {
discrip = eventBus.on<CustomEvent1>().listen((event) {
setState(() {
str = str + event._msg;
});
});
super.initState();
}
dispose() {
discrip.cancel(); //State销毁时,清理注册
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text(str);
}
}
class CustomEvent1 {
String _msg;
CustomEvent1(this._msg);
}
这里比价难记忆的是eventBus的on方法调用时返回的泛型,代码如下:
discrip = eventBus.on<CustomEvent1>().listen((event) {
setState(() {
str = str + event._msg;
});
});
其次是监听函数的返回值,一定要在dispose中进行销毁。
最后是通过eventBus调用fire方法发布消息,其参数就是开始时定义的消息类:
onPressed: () => {eventBus.fire(CustomEvent1('2222222'))},
总结:在flutter中使用eventBus和在其他框架中使用,原理层面没有差别,都是借助发布订阅模式,但是在使用时的细微之处需要记忆,不然在运用是就会卡壳这样不利于开发效率的提升。
以上,希望对你有所帮助。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。