天吶!你居然不知道Flutter中的"通知冒泡"

目錄傳送門:《Flutter快速上手指南》先導篇git

在 Flutter 中,有種由 Widget 樹下層往上層傳遞事件的機制,被稱爲 "通知冒泡"github

這種機制的實現,就是 NotificationListenerbash

使用 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

目錄傳送門:《Flutter快速上手指南》先導篇

如何找到我?

傳送門:CoorChice 的主頁

傳送門:CoorChice 的 Github

相關文章
相關標籤/搜索