Notification

通知(Notification) 是Flutter中一个重要的机制,在widget树中,每一个节点都可以分发通知,通知会沿着当前节点向上传递,所有父节点都可以通过 NotificationListener 来监听通知。 Flutter中将这种由子向父的传递通知的机制称为 通知冒泡(Notification Bubbling)。通知冒泡和用户触摸事件冒泡是相似的,但有一点不同:通知冒泡可以中止,但用户触摸事件不行

  • 通知冒泡和Web开发中浏览器事件冒泡原理是相似的,都是事件从出发源逐层向上传递
  • 我们可以在上层节点任意位置来监听通知/事件,也可以终止冒泡过程,终止冒泡后,通知将不会再向上传递

Flutter中很多地方使用了通知,如可滚动组件(Scrollable Widget)滑动时就会分发滚动通知(ScrollNotification),而Scrollbar正是通过监听ScrollNotification来确定滚动条位置的。

下面是一个监听可滚动组件滚动通知的例子:

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(new MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. debugShowCheckedModeBanner: true,
  8. title: 'NotificationListenerTest',
  9. theme: ThemeData(
  10. primarySwatch: Colors.blue,
  11. ),
  12. home: Scaffold(
  13. appBar: AppBar(title: Text("NotificationListenerTest")),
  14. body: NotificationListenerTest(),
  15. ));
  16. }
  17. }
  18. class NotificationListenerTest extends StatefulWidget {
  19. NotificationListenerTest({Key key}) : super(key: key);
  20. @override
  21. NotificationListenerTestState createState() => NotificationListenerTestState();
  22. }
  23. class NotificationListenerTestState extends State<NotificationListenerTest> {
  24. @override
  25. Widget build(BuildContext context) {
  26. return NotificationListener(
  27. onNotification: (notification) {
  28. switch (notification.runtimeType) {
  29. case ScrollStartNotification:
  30. print("开始滚动");
  31. break;
  32. case ScrollUpdateNotification:
  33. print("正在滚动");
  34. break;
  35. case ScrollEndNotification:
  36. print("滚动停止");
  37. break;
  38. case OverscrollNotification:
  39. print("滚动到边界");
  40. break;
  41. }
  42. },
  43. child: ListView.builder(
  44. itemCount: 100,
  45. itemBuilder: (context, index) {
  46. return ListTile(
  47. title: Text("$index"),
  48. );
  49. }),
  50. );
  51. }
  52. }

上例中的滚动通知如

  • ScrollStartNotification
  • ScrollUpdateNotification等

都是继承自 ScrollNotification 类,不同类型的通知子类会包含不同的信息,比如ScrollUpdateNotification有一个scrollDelta属性,它记录了移动的位移,其它通知属性读者可以自己查看SDK文档。

上例中,我们通过NotificationListener来监听子ListView的滚动通知的,NotificationListener定义如下:

  1. class NotificationListener<T extends Notification> extends StatelessWidget {
  2. const NotificationListener({
  3. Key key,
  4. @required this.child,
  5. this.onNotification,
  6. }) : super(key: key);
  7. ...//省略无关代码
  8. }

我们可以看到:

  • NotificationListener 继承自StatelessWidget类,所以它可以直接嵌套到Widget树中。
  • NotificationListener 可以指定一个模板参数,该模板参数类型必须是继承自Notification;当显式指定模板参数时,NotificationListener 便只会接收该参数类型的通知。

举个例子,如果我们将上例子代码给为:

  1. //指定监听通知的类型为滚动结束通知(ScrollEndNotification)
  2. NotificationListener<ScrollEndNotification>(
  3. onNotification: (notification){
  4. //只会在滚动结束时才会触发此回调
  5. print(notification);
  6. },
  7. child: ListView.builder(
  8. itemCount: 100,
  9. itemBuilder: (context, index) {
  10. return ListTile(title: Text("$index"),);
  11. }
  12. ),
  13. );
  • 上面代码运行后便只会在滚动结束时在控制台打印出通知的信息。
  • onNotification回调为通知处理回调,其函数签名如下:

    1. typedef NotificationListenerCallback<T extends Notification> = bool Function(T notification);
  • 它的返回值类型为布尔值,当返回值为true时,阻止冒泡,其父级Widget将再也收不到该通知;当返回值为false 时继续向上冒泡通知。

Flutter的UI框架实现中,除了在可滚动组件在滚动过程中会发出ScrollNotification之外,还有一些其它的通知,如

  • SizeChangedLayoutNotification
  • KeepAliveNotification
  • LayoutChangedNotification等

Flutter正是通过这种通知机制来使父元素可以在一些特定时机来做一些事情

自定义通知

除了Flutter内部通知,我们也可以自定义通知,下面我们看看如何实现自定义通知:

  1. 定义一个通知类,要继承自Notification类;

    1. class MyNotification extends Notification {
    2. MyNotification(this.msg);
    3. final String msg;
    4. }
  2. 分发通知

    • Notification有一个dispatch(context)方法,它是用于分发通知的,我们说过context实际上就是操作Element的一个接口,它与Element树上的节点是对应的,通知会从context对应的Element节点向上冒泡。

下面我们看一个完整的例子:

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(new MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. debugShowCheckedModeBanner: true,
  8. title: 'NotificationRoute',
  9. theme: ThemeData(
  10. primarySwatch: Colors.blue,
  11. ),
  12. home: Scaffold(
  13. appBar: AppBar(title: Text("NotificationRoute")),
  14. body: NotificationRoute(),
  15. ));
  16. }
  17. }
  18. class NotificationRoute extends StatefulWidget {
  19. @override
  20. NotificationRouteState createState() {
  21. return new NotificationRouteState();
  22. }
  23. }
  24. class NotificationRouteState extends State<NotificationRoute> {
  25. String _msg="";
  26. @override
  27. Widget build(BuildContext context) {
  28. //监听通知
  29. return NotificationListener<MyNotification>(
  30. onNotification: (notification) {
  31. setState(() {
  32. _msg+=notification.msg+" ";
  33. });
  34. return true;
  35. },
  36. child: Center(
  37. child: Column(
  38. mainAxisSize: MainAxisSize.min,
  39. children: <Widget>[
  40. // RaisedButton(
  41. // onPressed: () => MyNotification("Hi").dispatch(context),
  42. // child: Text("Send Notification"),
  43. // ),
  44. Builder(
  45. builder: (context) {
  46. return RaisedButton(
  47. //按钮点击时分发通知
  48. onPressed: () => MyNotification("Hi").dispatch(context),
  49. child: Text("Send Notification"),
  50. );
  51. },
  52. ),
  53. Text(_msg)
  54. ],
  55. ),
  56. ),
  57. );
  58. }
  59. }
  60. class MyNotification extends Notification {
  61. MyNotification(this.msg);
  62. final String msg;
  63. }

整改上面的类
  1. import 'package:flutter/material.dart';
  2. void main() => runApp(new MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. debugShowCheckedModeBanner: true,
  8. title: 'NotificationRoute',
  9. theme: ThemeData(
  10. primarySwatch: Colors.blue,
  11. ),
  12. home: Scaffold(
  13. appBar: AppBar(title: Text("NotificationRoute")),
  14. body: NotificationRoute(),
  15. ));
  16. }
  17. }
  18. class NotificationRoute extends StatefulWidget {
  19. @override
  20. NotificationRouteState createState() {
  21. return new NotificationRouteState();
  22. }
  23. }
  24. class NotificationRouteState extends State<NotificationRoute> {
  25. String _msg = "";
  26. @override
  27. Widget build(BuildContext context) {
  28. //监听通知
  29. return NotificationListener<MyNotification>(
  30. onNotification: (notification) {
  31. setState(() {
  32. _msg += notification.msg + " ";
  33. });
  34. return true;
  35. },
  36. child: Center(
  37. child: Column(
  38. mainAxisSize: MainAxisSize.min,
  39. children: <Widget>[DistributionNotice(), Text(_msg)],
  40. ),
  41. ),
  42. );
  43. }
  44. }
  45. class DistributionNotice extends StatelessWidget {
  46. const DistributionNotice({Key key}) : super(key: key);
  47. @override
  48. Widget build(BuildContext context) {
  49. return RaisedButton(
  50. //按钮点击时分发通知
  51. onPressed: () => MyNotification("Hi").dispatch(context),
  52. child: Text("Send Notification"),
  53. );
  54. }
  55. }
  56. class MyNotification extends Notification {
  57. MyNotification(this.msg);
  58. final String msg;
  59. }

上面代码中,我们每点一次按钮就会分发一个MyNotification类型的通知,我们在Widget根上监听通知,收到通知后我们将通知通过Text显示在屏幕上。

注意:代码中注释的部分是不能正常工作的,因为这个context是根Context,而NotificationListener是监听的子树,所以我们通过Builder来构建RaisedButton,来获得按钮位置的context。

运行效果如图所示:
通知(Notification) - 图1

阻止冒泡

我们将上面的例子改为:

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(new MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. debugShowCheckedModeBanner: true,
  8. title: 'NotificationRoute',
  9. theme: ThemeData(
  10. primarySwatch: Colors.blue,
  11. ),
  12. home: Scaffold(
  13. appBar: AppBar(title: Text("NotificationRoute")),
  14. body: NotificationRoute(),
  15. ));
  16. }
  17. }
  18. class NotificationRoute extends StatefulWidget {
  19. @override
  20. NotificationRouteState createState() {
  21. return new NotificationRouteState();
  22. }
  23. }
  24. class NotificationRouteState extends State<NotificationRoute> {
  25. String _msg = "";
  26. @override
  27. Widget build(BuildContext context) {
  28. //监听通知
  29. return NotificationListener<MyNotification>(
  30. onNotification: (notification) {
  31. print(notification.msg); //打印通知
  32. return false;
  33. },
  34. child: NotificationListener<MyNotification>(
  35. onNotification: (notification) {
  36. setState(() {
  37. _msg += notification.msg + " ";
  38. });
  39. return false;
  40. },
  41. child: Center(
  42. child: Column(
  43. mainAxisSize: MainAxisSize.min,
  44. children: <Widget>[DistributionNotice(), Text(_msg)],
  45. ),
  46. ),
  47. ),
  48. );
  49. }
  50. }
  51. class DistributionNotice extends StatelessWidget {
  52. const DistributionNotice({Key key}) : super(key: key);
  53. @override
  54. Widget build(BuildContext context) {
  55. return RaisedButton(
  56. //按钮点击时分发通知
  57. onPressed: () => MyNotification("Hi").dispatch(context),
  58. child: Text("Send Notification"),
  59. );
  60. }
  61. }
  62. class MyNotification extends Notification {
  63. MyNotification(this.msg);
  64. final String msg;
  65. }

上列中两个NotificationListener进行了嵌套,

  • 子NotificationListener的onNotification回调返回了false,表示不阻止冒泡,所以父NotificationListener仍然会受到通知,所以控制台会打印出通知信息;
  • 如果将子NotificationListener的onNotification回调的返回值改为true,表示阻止冒泡,则父NotificationListener便不会再打印通知了,因为子NotificationListener已经终止通知冒泡了。

    通知冒泡原理

    我们在上面介绍了通知冒泡的现象及使用,现在我们更深入一些,介绍一下Flutter框架中是如何实现通知冒泡的。为了搞清楚这个问题,就必须看一下源码,我们从通知分发的的源头出发,然后再顺藤摸瓜。由于通知是通过Notification的dispatch(context)方法发出的,那我们先看看dispatch(context)方法中做了什么,下面是相关源码:

    1. void dispatch(BuildContext target) {
    2. target?.visitAncestorElements(visitAncestor);
    3. }
  • dispatch(context)中调用了当前context的visitAncestorElements方法,该方法会从当前Element开始向上遍历父级元素;

  • visitAncestorElements有一个遍历回调参数,在遍历过程中对遍历到的父级元素都会执行该回调。
    • 遍历的终止条件是:已经遍历到根Element或某个遍历回调返回false
  • 源码中传给visitAncestorElements方法的遍历回调为visitAncestor方法,我们看看visitAncestor方法的实现:

    1. //遍历回调,会对每一个父级Element执行此回调
    2. bool visitAncestor(Element element) {
    3. //判断当前element对应的Widget是否是NotificationListener。
    4. //由于NotificationListener是继承自StatelessWidget,
    5. //故先判断是否是StatelessElement
    6. if (element is StatelessElement) {
    7. //是StatelessElement,则获取element对应的Widget,判断
    8. //是否是NotificationListener 。
    9. final StatelessWidget widget = element.widget;
    10. if (widget is NotificationListener<Notification>) {
    11. //是NotificationListener,则调用该NotificationListener的_dispatch方法
    12. if (widget._dispatch(this, element))
    13. return false;
    14. }
    15. }
    16. return true;
    17. }

    visitAncestor会判断每一个遍历到的父级Widget是否是 NotificationListener,

  • 如果不是,则返回true继续向上遍历

  • 如果是,则调用NotificationListener的_dispatch方法

我们看看_dispatch方法的源码:

  1. bool _dispatch(Notification notification, Element element) {
  2. // 如果通知监听器不为空,并且当前通知类型是该NotificationListener
  3. // 监听的通知类型,则调用当前NotificationListener的onNotification
  4. if (onNotification != null && notification is T) {
  5. final bool result = onNotification(notification);
  6. // 返回值决定是否继续向上遍历
  7. return result == true;
  8. }
  9. return false;
  10. }

我们可以看到 NotificationListener 的onNotification回调最终是在_dispatch方法中执行的,然后会根据返回值来确定是否继续向上冒泡。上面的源码实现其实并不复杂,通过阅读这些源码,一些额外的点读者可以注意一下:

  • Context上也提供了遍历Element树的方法。
  • 我们可以通过Element.widget得到element节点对应的widget;我们已经反复讲过Widget和Element的对应关系,读者通过这些源码来加深理解。

总结

Flutter中通过通知冒泡实现了一套自低向上的消息传递机制,这个和Web开发中浏览器的事件冒泡原理类似,Web开发者可以类比学习。另外我们通过源码了解了Flutter 通知冒泡的流程和原理,便于读者加深理解和学习Flutter的框架设计思想,在此,再次建议读者在平时学习中能多看看源码,定会受益匪浅。