Flutter Notification 使用说明

概述

在Flutter进行界面开发时,我们经常会遇到数据传递的问题。由于Flutter采用节点树的方式组织页面,以致于一个普通页面的节点层级会很深。当我们需要在子节点向父节点传递一些信息时,我们不可能层层传递Listener,所以我们需要一种在子节点跨层级传递消息的方式。

所幸,Flutter的Notification为我们提供了这样的能力。

使用方法

创建Notification

  1. class TestNotification extends Notification {
  2. TestNotification({
  3. @required this.count,
  4. });
  5. final int count;
  6. }

我们在Notification中定义我们要传递的信息,本例中,我们只传递一个Int型。

创建NotificationListener节点

NotificationListener继承了StatelessWidget。我们在一个较高的父节点,使用NotificationListener,就可以监听来自子节点的消息了。

  1. class GrandParentWidget extends StatelessWidget {
  2. @override
  3. Widget build(BuildContext context) {
  4. return Scaffold(
  5. appBar: new AppBar(
  6. title: new Text('Notification Demo'),
  7. ),
  8. body: NotificationListener<TestNotification>(
  9. child: ParentWidget(),
  10. onNotification: (TestNotification n){
  11. print('随机数:${n.count}');
  12. return true;
  13. },
  14. ),
  15. );
  16. }
  17. }

发送Notification

  1. class ButtonWidget extends StatelessWidget {
  2. @override
  3. Widget build(BuildContext context) {
  4. return Center(
  5. child: GestureDetector(
  6. child: Text("Click Me"),
  7. onTap: () {
  8. new TestNotification(count: new Random().nextInt(100))
  9. .dispatch(context);
  10. },
  11. ),
  12. );
  13. }
  14. }

原理

Notification

我们先来看看Notification的实现。Notification的实现非常简单,阅读源码时实属福利。

  1. /// A notification that can bubble up the widget tree.
  2. ///
  3. /// You can determine the type of a notification using the `is` operator to
  4. /// check the [runtimeType] of the notification.
  5. ///
  6. /// To listen for notifications in a subtree, use a [NotificationListener].
  7. ///
  8. /// To send a notification, call [dispatch] on the notification you wish to
  9. /// send. The notification will be delivered to any [NotificationListener]
  10. /// widgets with the appropriate type parameters that are ancestors of the given
  11. /// [BuildContext].
  12. abstract class Notification {
  13. /// Abstract const constructor. This constructor enables subclasses to provide
  14. /// const constructors so that they can be used in const expressions.
  15. const Notification();
  16. /// Applied to each ancestor of the [dispatch] target.
  17. ///
  18. /// The [Notification] class implementation of this method dispatches the
  19. /// given [Notification] to each ancestor [NotificationListener] widget.
  20. ///
  21. /// Subclasses can override this to apply additional filtering or to update
  22. /// the notification as it is bubbled (for example, increasing a `depth` field
  23. /// for each ancestor of a particular type).
  24. @protected
  25. @mustCallSuper
  26. bool visitAncestor(Element element) {
  27. if (element is StatelessElement) {
  28. final StatelessWidget widget = element.widget;
  29. if (widget is NotificationListener<Notification>) {
  30. if (widget._dispatch(this, element)) // that function checks the type dynamically
  31. return false;
  32. }
  33. }
  34. return true;
  35. }
  36. /// Start bubbling this notification at the given build context.
  37. ///
  38. /// The notification will be delivered to any [NotificationListener] widgets
  39. /// with the appropriate type parameters that are ancestors of the given
  40. /// [BuildContext]. If the [BuildContext] is null, the notification is not
  41. /// dispatched.
  42. void dispatch(BuildContext target) {
  43. // The `target` may be null if the subtree the notification is supposed to be
  44. // dispatched in is in the process of being disposed.
  45. target?.visitAncestorElements(visitAncestor);
  46. }
  47. ...
  48. }

除了注释之外,Notification的核心代码只有十行左右。主要包含了visitAncestor和dispatch两个方法。

我们在调用dispatch后,会调用visitAncestorElements。

  1. /// Walks the ancestor chain, starting with the parent of this build context's
  2. /// widget, invoking the argument for each ancestor. The callback is given a
  3. /// reference to the ancestor widget's corresponding [Element] object. The
  4. /// walk stops when it reaches the root widget or when the callback returns
  5. /// false. The callback must not return null.
  6. ///
  7. /// This is useful for inspecting the widget tree.
  8. ///
  9. /// Calling this method is relatively expensive (O(N) in the depth of the tree).
  10. ///
  11. /// This method should not be called from [State.deactivate] or [State.dispose]
  12. /// because the element tree is no longer stable at that time. To refer to
  13. /// an ancestor from one of those methods, save a reference to the ancestor
  14. /// by calling [visitAncestorElements] in [State.didChangeDependencies].
  15. void visitAncestorElements(bool visitor(Element element)) {
  16. assert(_debugCheckStateIsActiveForAncestorLookup());
  17. Element ancestor = _parent;
  18. while (ancestor != null && visitor(ancestor))
  19. ancestor = ancestor._parent;
  20. }

visitAncestorElements是framework.dart中的方法,从注释中我们可以比较容易理解,这个方法主要是Flutter为我们提供的Widget向上遍历的方法。在调用方法时,我们需要传入一个visitor方法,当visitor方法返回false时,遍历终止。

到这里,我们就明白了,Notification的dispatch方法,其实是向上遍历,寻找符合条件的父节点,然后进行处理。接下来我们看下Notification的visitor。

  1. /// Applied to each ancestor of the [dispatch] target.
  2. ///
  3. /// The [Notification] class implementation of this method dispatches the
  4. /// given [Notification] to each ancestor [NotificationListener] widget.
  5. ///
  6. /// Subclasses can override this to apply additional filtering or to update
  7. /// the notification as it is bubbled (for example, increasing a `depth` field
  8. /// for each ancestor of a particular type).
  9. @protected
  10. @mustCallSuper
  11. bool visitAncestor(Element element) {
  12. if (element is StatelessElement) {
  13. final StatelessWidget widget = element.widget;
  14. if (widget is NotificationListener<Notification>) {
  15. if (widget._dispatch(this, element)) // that function checks the type dynamically
  16. return false;
  17. }
  18. }
  19. return true;
  20. }

实现非常简单,就是判断element的widget是否为NotificationListener,然后进行分发。如果分发的返回true,则visitAncestor返回false,遍历终止。

在使用时,我们可以重写visitAncestor方法,来修改遍历的检查判断。

NotificationListener

将下来,我们看一下NotificationListener的实现。

  1. /// A widget that listens for [Notification]s bubbling up the tree.
  2. ///
  3. /// Notifications will trigger the [onNotification] callback only if their
  4. /// [runtimeType] is a subtype of `T`.
  5. ///
  6. /// To dispatch notifications, use the [Notification.dispatch] method.
  7. class NotificationListener<T extends Notification> extends StatelessWidget {
  8. /// Creates a widget that listens for notifications.
  9. const NotificationListener({
  10. Key key,
  11. @required this.child,
  12. this.onNotification,
  13. }) : super(key: key);
  14. /// The widget directly below this widget in the tree.
  15. ///
  16. /// This is not necessarily the widget that dispatched the notification.
  17. ///
  18. /// {@macro flutter.widgets.child}
  19. final Widget child;
  20. /// Called when a notification of the appropriate type arrives at this
  21. /// location in the tree.
  22. ///
  23. /// Return true to cancel the notification bubbling. Return false (or null) to
  24. /// allow the notification to continue to be dispatched to further ancestors.
  25. ///
  26. /// The notification's [Notification.visitAncestor] method is called for each
  27. /// ancestor, and invokes this callback as appropriate.
  28. ///
  29. /// Notifications vary in terms of when they are dispatched. There are two
  30. /// main possibilities: dispatch between frames, and dispatch during layout.
  31. ///
  32. /// For notifications that dispatch during layout, such as those that inherit
  33. /// from [LayoutChangedNotification], it is too late to call [State.setState]
  34. /// in response to the notification (as layout is currently happening in a
  35. /// descendant, by definition, since notifications bubble up the tree). For
  36. /// widgets that depend on layout, consider a [LayoutBuilder] instead.
  37. final NotificationListenerCallback<T> onNotification;
  38. bool _dispatch(Notification notification, Element element) {
  39. if (onNotification != null && notification is T) {
  40. final bool result = onNotification(notification);
  41. return result == true; // so that null and false have the same effect
  42. }
  43. return false;
  44. }
  45. @override
  46. Widget build(BuildContext context) => child;
  47. }

我们可以看到,dispatch方法,只是进行了一些简单的类型检查,然后就调用我们传入的notification方法了。这里值得注意的是,只有当我们notification返回true时,遍历才会终止。

以上就是Flutter中Notification的基本原理和使用方法。