通知可以用来监听事件,用来刷新页面,先看通知的源码:
class NotificationListener<T extends Notification> extends ProxyWidget {
/// Creates a widget that listens for notifications.
const NotificationListener({
super.key,
required super.child,
this.onNotification,
});
final NotificationListenerCallback<T>? onNotification;
Element createElement() {
return _NotificationElement<T>(this);
}
}
从源码可以看出,一般使用方式需要先创建一个继承自 Notification 的类,例如:
class MyNotification extends Notification {
String value;
dynamic data;
MyNotification(this.value, {this.data});
}
使用 NotificationListener<MyNotification>(),onNotification 是一个通知回调,其中有个参数 notification ,也就是 MyNotification 的实例对象:
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.white,
child: NotificationListener<MyNotification>(
onNotification: (notification) {
if (notification.value == "todo") {
/// do something
}
/// retuen true
return true;
},
/// 子组件
child: ...,
),
),
);
}
在子组件中发送通知:
ElevatedButton(
/// 按钮点击时分发通知
onPressed: () => MyNotification("todo").dispatch(context),
child: Text("Send Notification"),
);
如果在同一个类中获取 dispatch(context) 获取 context 可能会出问题,可以使用嵌套一层 Builder 组件来获取 context :
Builder(
builder: (context) {
return ...;
},
);
文章介绍了Flutter中如何使用NotificationListener监听自定义Notification事件,通过创建继承自Notification的类,设置回调函数处理事件,在子组件触发通知并利用Builder获取正确的BuildContext。示例展示了发送和接收通知的过程。

827

被折叠的 条评论
为什么被折叠?



