天呐!你竟然不知道Flutter中的"通知冒泡"

2,862 阅读1分钟

目录传送门:《Flutter快速上手指南》先导篇

在 Flutter 中,有种由 Widget 树下层往上层传递事件的机制,被称为 "通知冒泡"

这种机制的实现,就是 NotificationListener

使用 NotificationListener 可以监听格式各样的事件通知。

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 开始的视图树中的各个节点发出的。

比如,可滑动的 Widget 都会发出 ScrollNotification 系列的事件通知,你可以使用 NotificationListener 包裹它们,然后开始接收这些事件通知。

现在,看看如何发送一个自定义的事件通知。

1.先自定义一个 Notification

class MyNotification extends Notification {
  MyNotification(this.msg);
  final String msg;
}

2.在子节点中发送通知

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。

目录传送门:《Flutter快速上手指南》先导篇

如何找到我?

传送门:CoorChice 的主页

传送门:CoorChice 的 Github