在 Flutter 中,有种由 Widget 树下层往上层传递事件的机制,被称为 "通知冒泡"。github
这种机制的实现,就是 NotificationListener。bash
使用 NotificationListener 能够监听格式各样的事件通知。post
NotificationListener(
// 此处可以收到各类各样的事件
onNotification: (notify) {
switch (notify.runtimeType) {
case ScrollStartNotification:
print("ScrollStart");
break;
case ScrollUpdateNotification:
print("ScrollUpdate");
break;
case ScrollEndNotification:
print("ScrollEnd");
break;
case OverscrollNotification:
print("Overscroll");
break;
case LayoutChangedNotification:
print("LayoutChanged");
break;
case SizeChangedLayoutNotification:
print("SizeChangedLayout");
break;
case UserScrollNotification:
print("UserScroll");
break;
case KeepAliveNotification:
print("KeepAlive");
break;
case MyNotification:
print("CustomScroll");
break;
}
},
child: MyWidget())
复制代码
这些事件,是来自于由 child
开始的视图树中的各个节点发出的。ui
好比,可滑动的 Widget 都会发出 ScrollNotification 系列的事件通知,你能够使用 NotificationListener 包裹它们,而后开始接收这些事件通知。this
如今,看看如何发送一个自定义的事件通知。spa
1.先自定义一个 Notification3d
class MyNotification extends Notification {
MyNotification(this.msg);
final String msg;
}
复制代码
2.在子节点中发送通知code
Builder(builder: (context) {
return GestureDetector(
onTap: () {
// 只须要调用 dispatch 便可
MyNotification('Haha!').dispatch(context);
},
child: Container(
width: 100,
height: 100,
color: Colors.blue,
),
);
}
复制代码
⚠️ 注意,因为 dispatch()
须要节点的 context,而不是 build(BuildContext context)
中的根 context,因此须要使用 Builder,包裹一下节点 Widget,以得到该位置的 context。cdn