通知を使用してイベントをリッスンし、ページを更新できます。まず、通知のソース コードを確認します。
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 ...;
},
);