在使用flutter开发过程中有些时候需要在父子组件之间进行通讯,我们可以借助notification来实现。实现步骤如下:
1、定义消息盒子
2、在子组件中通过消息盒子发布消息
3、父组件在child位置调用NotificationListener并传递参数,两个固定参数,onNotification与child。
实现代码如下:
//定义消息盒子
class CustomNotification extends Notification {
CustomNotification(this.msg);
final String msg;
}
//在子组件中使用消息盒子发布信息
class CustomChild extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
//按钮点击时分发通知
onPressed: () => CustomNotification("Hi").dispatch(context),
child: Text("Fire Notification"),
);
}
}
class _MyHomePageState extends State<MyHomePage> {
String _msg = "通知:";
@override
Widget build(BuildContext context) {
//父组件监听消息,如何监听呢,通过包裹在NotificationListener组件中来实现.
return NotificationListener<CustomNotification>(
onNotification: (notification) {
setState(() {_msg += notification.msg+" ";});//收到子Widget通知,更新msg
},
child:Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[Text(_msg),CustomChild()],//将子Widget加入到视图树中
)
);
}
}
仔细阅读源码我们发现,消息盒子发布消息后,父组件通过onNotification函数监听到,并得到传递的消息,然后改变自己的属性。
总结一下,在使用Notification进行父子组件通信时一般使用的是子组件向父组件通信,代码结构主要分为三个部分:
1、消息盒子消息盒子继承Notification,构造函数定义参数数据类型。
2、第二部分是子组件,自组件内部定义事件,通过事件调用消息盒子的dispatch事件,使用方法为实例化消息盒子,调用dispatch方法,参数为context。
3、第三部分为父组件,父组件需要被NotificationListener函数包裹,需要设置两个参数child为父组件页面结构,关键是onNotification函数,这个函数监听消息盒子的dispatch方法的调用,其参数notification上携带消息盒子传递的参数。
以上便是使用Notifacation进行父子组件通信的方法,希望对你有所帮助。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有