Flutter 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);
  }
}

从源码可以看出,一般使用方式需要先创建一个继承自 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 ...;
	},
);

猜你喜欢

转载自blog.csdn.net/SSY_1992/article/details/131702903