Flutter框架中开发者可以通过继承Notification类,自定义通知事件,如
class MyNotification extends Notification {
late dynamic details;
MyNotification(this.details);
}
当需要发送通知的时候,可以通过调用Notification类的dispatch方法触发通知。例如当用户点击按钮时发出通知,并将Colors.red和字符串作为通知细节,传给该自定义通知的构造体。
Wrap(
spacing: 20,
children: [
ElevatedButton(onPressed: (){
MyNotification(Colors.red).dispatch(context);
}, child: Text("发送颜色通知")),
ElevatedButton(onPressed: (){
MyNotification("这里是字符串").dispatch(context);
}, child: Text('发送字符串通知'))
],
);
若组件树的上级插入NotificationListener组件,即可在MuNotification被用户触发时收到该通知。由于NotificationListener还可能会收到其他组件发出的其他通知,因此需要对收到的通知类型进行判断此处即需要判断是否是MyNotification类。用来避免受到其他无关通知的干扰:
NotificationListener(
onNotification: (Notification notification){
if(notification is MyNotification){
print(notification.details);
return true;
}
return false;
},
child: Sender())
完整代码为:
import 'package:flutter/material.dart';
main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
const MyHome({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor:Colors.white60,
body:MyBody(),
);
}
}
class MyBody extends StatelessWidget {
const MyBody({super.key});
@override
Widget build(BuildContext context) {
return NotificationListener(
onNotification: (Notification notification){
if(notification is MyNotification){
print(notification.details);
return true;
}
return false;
},
child: Sender());
}
}
class Sender extends StatelessWidget{
@override
Widget build(BuildContext context){
return Wrap(
spacing: 20,
children: [
ElevatedButton(onPressed: (){
MyNotification(Colors.red).dispatch(context);
}, child: Text("发送颜色通知")),
ElevatedButton(onPressed: (){
MyNotification("这里是字符串").dispatch(context);
}, child: Text('发送字符串通知'))
],
);
}
}
class MyNotification extends Notification{
late dynamic details;
MyNotification(this.details);
}
NotificationListener只会监听子级(children)和其他下级(descendants)组件发出的通知事件,而无法监听到父级和上级的组件,也不会监听本身或者同级发出的通知事件,因此在这个例子中,NotificationListener的child属性传入的是自定义的Sender组件,而不是直接嵌套Column完成组件构造,以确保发送通知事件的是子组件而不是本身。