Notifications can be used to listen for events and refresh the page. First, look at the source code of the notification:
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);
}
}
It can be seen from the source code that the general usage requires first creating a Notification
class inherited from , for example:
class MyNotification extends Notification {
String value;
dynamic data;
MyNotification(this.value, {
this.data});
}
Use NotificationListener<MyNotification>()
is onNotification
a notification callback, which has a parameter notification
, which is MyNotification
an instance object of:
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: ...,
),
),
);
}
Send notification in child component:
ElevatedButton(
/// 按钮点击时分发通知
onPressed: () => MyNotification("todo").dispatch(context),
child: Text("Send Notification"),
);
dispatch(context)
If you get it in the same class, context
there may be problems. You can use a nested Builder
component to get it context
:
Builder(
builder: (context) {
return ...;
},
);