Flutter Notification

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 Notificationclass inherited from , for example:

class MyNotification extends Notification {
    
    
    String value;
  	dynamic data;
	MyNotification(this.value, {
    
    this.data});
}

Use NotificationListener<MyNotification>()is onNotificationa notification callback, which has a parameter notification, which is MyNotificationan 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, contextthere may be problems. You can use a nested Buildercomponent to get it context:

Builder(
	builder: (context) {
    
    
		return ...;
	},
);

Guess you like

Origin blog.csdn.net/SSY_1992/article/details/131702903