Widget类本身是一个抽象类,其中最核心的就是定义了createElement()接口,在 Flutter 开发中,我们一般都不用直接继承Widget类来实现一个新组件,相反,我们通常会通过继承StatelessWidget或StatefulWidget来间接继承widget类来实现。StatelessWidget和StatefulWidget都是直接继承自Widget类,而这两个类也正是 Flutter 中非常重要的两个抽象类,它们引入了两种 widget 模型,接下来我们将重点介绍一下这两个类。

一. StatelessWidget

StatelessWidget相对比较简单,它继承自Widget类,重写了createElement()方法:

  1. @override
  2. StatelessElement createElement() => new StatelessElement(this);

StatelessElement 间接继承自Element类,与StatelessWidget相对应(作为其配置数据)

/// A widget that does not require mutable state. /// /// A stateless widget is a widget that describes part of the user interface by /// building a constellation of other widgets that describe the user interface /// more concretely. The building process continues recursively until the /// description of the user interface is fully concrete (e.g., consists /// entirely of [RenderObjectWidget]s, which describe concrete [RenderObject]s).

/// Stateless widget are useful when the part of the user interface you are /// describing does not depend on anything other than the configuration /// information in the object itself and the [BuildContext] in which the widget /// is inflated. For compositions that can change dynamically, e.g. due to /// having an internal clock-driven state, or depending on some system state, /// consider using [StatefulWidget].

StatelessWidget 是不需要可变状态的widget。

无状态小部件是通过构建一组其他小部件来描述用户界面的一部分的 widget,在递归性的构建过程中直到用户界面的描述完全具体化 (例如,完全由[RenderObjectWidget]s组成,描述具体的[RenderObject]s)。
当您描述的用户界面部分不依赖于对象本身中的配置信息以及 widget 的 BuildContext 时,无状态widget非常有用,对于可以动态改变的组合,例如由于拥有内部时钟驱动状态,或依赖于某些系统状态,考虑使用[StatefulWidget]。

StatelessWidget 用于不需要维护状态的场景,它通常在 build 方法中通过嵌套其它 Widget 来构建UI,在构建过程中会递归的构建其嵌套的 Widget。我们看一个简单的例子:

  1. class Frog extends StatelessWidget {
  2. const Frog({
  3. Key key,
  4. this.color = const Color(0xFF2DBD3A),
  5. this.child,
  6. }) : super(key: key);
  7. final Color color;
  8. final Widget child;
  9. @override
  10. Widget build(BuildContext context) {
  11. return Container(color: color, child: child);
  12. }
  13. }

上面的代码,实现了一个Frog widget。

按照惯例,widget 的构造函数参数应使用命名参数,命名参数中的必要参数要添加 @required 标注,这样有利于静态代码分析器进行检查。另外,在继承 widget 时,第一个参数通常应该是 Key,另外,如果 Widget 需要接收子 Widget,那么 child 或 children 参数通常应被放在参数列表的最后。同样是按照惯例,Widget的属性应尽可能的被声明为 final,防止被意外改变。

然后我们可以通过如下方式使用它:

  1. Widget build(BuildContext context) {
  2. return Frog(color: Color(0xFF2DAA3A));
  3. }

image.png
build 方法有一个 context 参数,它是 BuildContext 类的一个实例,表示当前 widget 在 widget 树中的上下文,每一个 widget 都会对应一个 context 对象(因为每一个 widget 都是 widget 树上的一个节点)。实际上,context 是当前 widget 在 widget 树中位置中执行”相关操作“的一个句柄,BuildContext 就是 widget 对应的Element,这里暂时先不展开讲。

性能优化建议

/// ## Performance considerations /// /// The [build] method of a stateless widget is typically only called in three /// situations: the first time the widget is inserted in the tree, when the /// widget’s parent changes its configuration, and when an [InheritedWidget] it /// depends on changes. /// /// If a widget’s parent will regularly change the widget’s configuration, or if /// it depends on inherited widgets that frequently change, then it is important /// to optimize the performance of the [build] method to maintain a fluid /// rendering performance.

无状态小部件的[build]方法通常仅在三种情况下调用:

  • 第一次将小部件插入树中时;
  • 小部件的父级更改其配置时;
  • 当[InheritedWidget]依赖于更改时;

如果小部件的父部件将定期更改小部件的配置,或者如果它依赖于经常更改的继承小部件,则优化[build]方法的性能以保持渲染性能非常重要。

/// There are several techniques one can use to minimize the impact of /// rebuilding a stateless widget: /// /// * Minimize the number of nodes transitively created by the build method and /// any widgets it creates. For example, instead of an elaborate arrangement /// of [Row]s, [Column]s, [Padding]s, and [SizedBox]es to position a single /// child in a particularly fancy manner, consider using just an [Align] or a /// [CustomSingleChildLayout]. Instead of an intricate layering of multiple /// [Container]s and with [Decoration]s to draw just the right graphical /// effect, consider a single [CustomPaint] widget. /// /// * Use const widgets where possible, and provide a const constructor for /// the widget so that users of the widget can also do so. /// /// * Consider refactoring the stateless widget into a stateful widget so that /// it can use some of the techniques described at [StatefulWidget], such as /// caching common parts of subtrees and using [GlobalKey]s when changing the /// tree structure. /// /// * If the widget is likely to get rebuilt frequently due to the use of /// [InheritedWidget]s, consider refactoring the stateless widget into /// multiple widgets, with the parts of the tree that change being pushed to /// the leaves. For example instead of building a tree with four widgets, the /// inner-most widget depending on the [Theme], consider factoring out the /// part of the build function that builds the inner-most widget into its own /// widget, so that only the inner-most widget needs to be rebuilt when the /// theme changes.

有几种方法可用于最小化重新构建SataelessWidget的影响:

  • 最小化build方法及其创建的任何小部件创建的节点数。例如,不是用[Row] s、[Column] s、[Padding] s和[SizedBox ] es进行精心安排以一种花哨的方式定位一个孩子,而是考虑只使用[Align]或[CustomSingleChildLayout]。与其使用复杂的多层结构的[Container]s和[Decoration]s画出正确的图形效果,不如考虑使用单个[CustomPaint] widget。
  • 尽可能使用const小部件,并为小部件提供const构造函数,以便小部件的用户也可以这样做。
  • 考虑将StatelessWidget重构为StatefulWidget,以便它可以使用[StatefulWidget ]中描述的一些技术,例如缓存子树的公共部分,以及在更改树结构时使用[GlobalKey] S。
  • 如果由于因为使用[InheritedWidget] s而频繁地重构小部件,考虑将无状态控件分解为多个小部件,作为树各个部分的节点。例如,与其使用四个小部件构建树(最内层小部件依赖于[Theme]),不如考虑将最内层widget 的分解构建为它自己的widget,以便当Theme改变时,只需要重建这个最内部的小部件即可。

二. StatefulWidget

和 StatelessWidget 一样,StatefulWidget 也是继承自 Widget 类,并重写了 createElement() 方法,不同的是返回的 Element 对象并不相同;
另外StatefulWidget类中添加了一个新的接口createElement()。

下面我们看看StatefulWidget的类定义:

  1. abstract class StatefulWidget extends Widget {
  2. const StatefulWidget({ Key key }) : super(key: key);
  3. @override
  4. StatefulElement createElement() => new StatefulElement(this);
  5. @protected
  6. State createState();
  7. }
  • StatefulElement 间接继承自 Element 类,与 StatefulWidget 相对应(作为其配置数据)。StatefulElement 中可能会多次调用 createState() 来创建状态(State)对象。
  • createState() 用于创建和 StatefulWidget 相关的状态,它在 StatefulWidget 的生命周期中可能会被多次调用。例如,当一个 StatefulWidget 同时插入到 widget 树的多个位置时,Flutter framework 就会调用该方法为每一个位置生成一个独立的 State 实例,其实,本质上就是一个 StatefulElement 对应一个State实例。

接下来我们按照文档一部分一部分的看,部分与 StatelessWidget 相同的文档将不在展示.

  1. /// A widget that has mutable state.
  2. ///
  3. /// State is information that (1) can be read synchronously when the widget is
  4. /// built and (2) might change during the lifetime of the widget. It is the
  5. /// responsibility of the widget implementer to ensure that the [State] is
  6. /// promptly notified when such state changes, using [State.setState].
  7. /// A stateful widget is a widget that describes part of the user interface by
  8. /// building a constellation of other widgets that describe the user interface
  9. /// more concretely. The building process continues recursively until the
  10. /// description of the user interface is fully concrete (e.g., consists
  11. /// entirely of [RenderObjectWidget]s, which describe concrete [RenderObject]s).
  12. ///
  13. /// Stateful widgets are useful when the part of the user interface you are
  14. /// describing can change dynamically, e.g. due to having an internal
  15. /// clock-driven state, or depending on some system state. For compositions that
  16. /// depend only on the configuration information in the object itself and the
  17. /// [BuildContext] in which the widget is inflated, consider using
  18. /// [StatelessWidget].

具有可变state的widget,state是(1)在小部件构建时可以同步读取的信息,以及(2)在小部件的生存期内可能更改的信息。widget 实现者有责任确保在状态发生变化时及时通知[State],使用[State.setState].
StatefulWidget是通过构建一组其他小部件来描述用户界面的一部分的 widget,在递归性的构建过程中直到用户界面的描述完全具体化 (例如,完全由[RenderObjectWidget]s组成,描述具体的[RenderObject]s)。
当你描述的部分用户界面可以动态改变时,有状态小部件是很有用的,例如由于有一个内部时钟驱动的状态,或者取决于某些系统状态。对于只依赖于对象本身的配置信息和小部件膨胀成的[BuildContext],考虑使用[StatelessWidget].

  1. /// [StatefulWidget] instances themselves are immutable and store their mutable
  2. /// state either in separate [State] objects that are created by the
  3. /// [createState] method, or in objects to which that [State] subscribes, for
  4. /// example [Stream] or [ChangeNotifier] objects, to which references are stored
  5. /// in final fields on the [StatefulWidget] itself.
  6. ///
  7. /// The framework calls [createState] whenever it inflates a
  8. /// [StatefulWidget], which means that multiple [State] objects might be
  9. /// associated with the same [StatefulWidget] if that widget has been inserted
  10. /// into the tree in multiple places. Similarly, if a [StatefulWidget] is
  11. /// removed from the tree and later inserted in to the tree again, the framework
  12. /// will call [createState] again to create a fresh [State] object, simplifying
  13. /// the lifecycle of [State] objects.

[StatefulWidget]实例本身是不可变的, 它们的可变状态存储在由[createState]方法创建的单独的[state]对象中,
或者存储在该[state]订阅的对象中,例如[Stream]或[ChangeNotifier]对象,其引用存储在[StatefulWidget]本身的最终字段中。

框架在 inflates [StatefulWidget]时调用[createState],这意味着如果多个[State]对象被插入到树的多个位置,那么多个[State]对象可能与同一个[StatefulWidget]相关联。
类似地,如果一个[StatefulWidget]从树中删除,然后再次插入到树中,框架将再次调用[createState]来创建一个新的[State]对象,从而简化[State]对象的生命周期。

  1. /// A [StatefulWidget] keeps the same [State] object when moving from one
  2. /// location in the tree to another if its creator used a [GlobalKey] for its
  3. /// [key]. Because a widget with a [GlobalKey] can be used in at most one
  4. /// location in the tree, a widget that uses a [GlobalKey] has at most one
  5. /// associated element. The framework takes advantage of this property when
  6. /// moving a widget with a global key from one location in the tree to another
  7. /// by grafting the (unique) subtree associated with that widget from the old
  8. /// location to the new location (instead of recreating the subtree at the new
  9. /// location). The [State] objects associated with [StatefulWidget] are grafted
  10. /// along with the rest of the subtree, which means the [State] object is reused
  11. /// (instead of being recreated) in the new location. However, in order to be
  12. /// eligible for grafting, the widget must be inserted into the new location in
  13. /// the same animation frame in which it was removed from the old location.

[StatefulWidget]将保持相同的[State]对象当它的创建者使用[GlobalKey]作为它的[key],从树中的一个位置移动到另一个位置时。 因为带有[GlobalKey]的widget最多只能在树中的一个位置使用,带[GlobalKey]的小部件最多有一个关联element。框架通过使用该属性,当将具有全局键的小部件从树中的一个位置移动到另一个位置时,框架会将与该小部件关联的(唯一的)子树从旧位置移植到新位置(而不是在新位置重新创建子树),与[StatefulWidget]关联的[State]对象与子树的其余部分一起被嫁接,这意味着[State]对象在新位置被重用(而不是被重新创建)。
但是,为了符合移植的条件,小部件必须在同一画帧中从旧位置移除并插入到新位置。

  1. /// There are two primary categories of [StatefulWidget]s.
  2. ///
  3. /// The first is one which allocates resources in [State.initState] and disposes
  4. /// of them in [State.dispose], but which does not depend on [InheritedWidget]s
  5. /// or call [State.setState]. Such widgets are commonly used at the root of an
  6. /// application or page, and communicate with subwidgets via [ChangeNotifier]s,
  7. /// [Stream]s, or other such objects. Stateful widgets following such a pattern
  8. /// are relatively cheap (in terms of CPU and GPU cycles), because they are
  9. /// built once then never update. They can, therefore, have somewhat complicated
  10. /// and deep build methods.
  11. ///
  12. /// The second category is widgets that use [State.setState] or depend on
  13. /// [InheritedWidget]s. These will typically rebuild many times during the
  14. /// application's lifetime, and it is therefore important to minimize the impact
  15. /// of rebuilding such a widget. (They may also use [State.initState] or
  16. /// [State.didChangeDependencies] and allocate resources, but the important part
  17. /// is that they rebuild.)

[StatefulWidget]有两个主要类别。

  • 一类是在[State.initState]中分配资源并在[State.dispose]中处置资源,但不依赖[InheritedWidget]s或调用[State.setState]. 这些小部件通常在应用程序或页面的根目录下使用,并通过[ChangeNotifier]s、[Stream]s或其他此类对象与子部件通信。遵循这种模式的有状态小部件相对廉价(在CPU和GPU周期方面),因为它们是在一次构建之后就不会更新的。因此,它们可以有一些复杂和深入的构建方法。
  • 第二类是使用[State.setState]或者依赖于[InheritedWidget]s,这类组件通常在应用程序的生命周期内会重建很多次,因此,将重建这样一个小部件的影响降到最低是非常重要的。(他们也可以使用[State.initState]或者[State.didChangeDependencies]分配资源,但重要的部分是它们的重建。)

性能优化影响

  1. /// There are several techniques one can use to minimize the impact of
  2. /// rebuilding a stateful widget:
  3. ///
  4. /// * Push the state to the leaves. For example, if your page has a ticking
  5. /// clock, rather than putting the state at the top of the page and
  6. /// rebuilding the entire page each time the clock ticks, create a dedicated
  7. /// clock widget that only updates itself.
  8. ///
  9. /// * Minimize the number of nodes transitively created by the build method and
  10. /// any widgets it creates. Ideally, a stateful widget would only create a
  11. /// single widget, and that widget would be a [RenderObjectWidget].
  12. /// (Obviously this isn't always practical, but the closer a widget gets to
  13. /// this ideal, the more efficient it will be.)
  14. ///
  15. /// * If a subtree does not change, cache the widget that represents that
  16. /// subtree and re-use it each time it can be used. It is massively more
  17. /// efficient for a widget to be re-used than for a new (but
  18. /// identically-configured) widget to be created. Factoring out the stateful
  19. /// part into a widget that takes a child argument is a common way of doing
  20. /// this.
  21. ///
  22. /// * Use `const` widgets where possible. (This is equivalent to caching a
  23. /// widget and re-using it.)
  24. ///
  25. /// * Avoid changing the depth of any created subtrees or changing the type of
  26. /// any widgets in the subtree. For example, rather than returning either the
  27. /// child or the child wrapped in an [IgnorePointer], always wrap the child
  28. /// widget in an [IgnorePointer] and control the [IgnorePointer.ignoring]
  29. /// property. This is because changing the depth of the subtree requires
  30. /// rebuilding, laying out, and painting the entire subtree, whereas just
  31. /// changing the property will require the least possible change to the
  32. /// render tree (in the case of [IgnorePointer], for example, no layout or
  33. /// repaint is necessary at all).
  34. ///
  35. /// * If the depth must be changed for some reason, consider wrapping the
  36. /// common parts of the subtrees in widgets that have a [GlobalKey] that
  37. /// remains consistent for the life of the stateful widget. (The
  38. /// [KeyedSubtree] widget may be useful for this purpose if no other widget
  39. /// can conveniently be assigned the key.)

有几种方法可用于最小化重新构建SataelessWidget的影响:

  • 把 state 放到页节点上。例如,如果您的页面有一个滴答作响的时钟,与其将 state 放在页面顶部,每次在时钟滴答作响时重建整个页面,不如创建一个只更新自身的专用时钟小部件。
  • 最小化由build方法及其创建的任何小部件以传递方式创建的节点数。理想情况下,一个有状态的小部件将只创建一个小部件,而该小部件将是一个[RenderObjectWidget]。(显然这并不总是可行的,但是小部件越接近这个理想状况,它的效率就越高。)
  • 如果子树没有改变,缓存该组件表示该小部件可以在每次可以使用它时重新使用它;重新使用一个小部件比创建一个新的(但配置相同的)小部件要高效得多。将有状态部分分解成一个接受子参数的小部件是一种常见的方法。
  • 尽可能使用“const”小部件。(这相当于缓存小部件并重新使用。)
  • 避免更改任何已创建子树的深度或更改子树中任何小部件的类型。例如,与其返回 child 或者被包裹在[IgnorePointer]中的子 child,不如始终用[IgnorePointer]包裹子部件并控制[IgnorePointer.ignoring]属性。这是因为更改子树的深度需要重建、布局和绘制整个子树,而仅更改属性就只需要对渲染树进行尽可能少的更改

    (例如,在[IgnorePointer]的情况下,根本不需要重新布局或绘制)。

  • 如果由于某种原因必须更改深度,请考虑将子树的公共部分包裹到具有在有状态小部件的生命周期内保持一致的[GlobalKey]的小部件中。(如果没有其他小部件可以方便地分配 key,[KeyedSubtree]小部件可以用于此目的。)

State

  1. /// The logic and internal state for a [StatefulWidget].
  2. ///
  3. /// State is information that (1) can be read synchronously when the widget is
  4. /// built and (2) might change during the lifetime of the widget. It is the
  5. /// responsibility of the widget implementer to ensure that the [State] is
  6. /// promptly notified when such state changes, using [State.setState].

由上面的文档可知: state 是 [StatefulWidget]的逻辑和内部状态,是(1)在小部件构建时可以同步读取的信息,以及(2)在小部件的生存期内可能更改的信息。Widget 实现者有责任确保在状态发生变化时及时通知[State],使用[State.setState]。一个 StatefulWidget 类会对应一个 State 类,State 表示与其对应的 StatefulWidget 要维护的状态,State 中的保存的状态信息可以:

  1. 在 widget 构建时可以被同步读取。
  2. 在 widget 生命周期中可以被改变,当 State 被改变时,可以手动调用其 setState() 方法通知 Flutter framework 状态发生改变,Flutter framework 在收到消息后,会重新调用其 build 方法重新构建 widget 树,从而达到更新UI的目的。
  1. /// [State] objects are created by the framework by calling the
  2. /// [StatefulWidget.createState] method when inflating a [StatefulWidget] to
  3. /// insert it into the tree. Because a given [StatefulWidget] instance can be
  4. /// inflated multiple times (e.g., the widget is incorporated into the tree in
  5. /// multiple places at once), there might be more than one [State] object
  6. /// associated with a given [StatefulWidget] instance. Similarly, if a
  7. /// [StatefulWidget] is removed from the tree and later inserted in to the tree
  8. /// again, the framework will call [StatefulWidget.createState] again to create
  9. /// a fresh [State] object, simplifying the lifecycle of [State] objects.

当[StatefulWidget]被膨胀插入到树时,[State]对象由框架通过调用 [StatefulWidget.createState]方法创建。因为给定的[StatefulWidget]实例可以膨胀多次(例如,该小部件一次在多个位置合并到树中),所以可能有多个[State]对象与给定的[StatefulWidget]实例关联。类似地,如果[StatefulWidget]从树中移除,然后再次插入到树中,框架将调用[StatefulWidget.createState]再次创建一个新的[State]对象,简化[State]对象的生命周期。

State 状态
  1. /// * The framework creates a [State] object by calling
  2. /// [StatefulWidget.createState].
  3. /// * The newly created [State] object is associated with a [BuildContext].
  4. /// This association is permanent: the [State] object will never change its
  5. /// [BuildContext]. However, the [BuildContext] itself can be moved around
  6. /// the tree along with its subtree. At this point, the [State] object is
  7. /// considered [mounted].

框架通过调用[StatefulWidget.createState]来创建[State]对象。
新创建的[State]对象与[BuildContext]关联,此关联是永久的,[State]对象永远不会更改其 [BuildContext]。但是,[BuildContext]本身可以在树及其子树周围移动。此时,[State]对象被认为是[mounted]。

  1. /// * The framework calls [initState]. Subclasses of [State] should override
  2. /// [initState] to perform one-time initialization that depends on the
  3. /// [BuildContext] or the widget, which are available as the [context] and
  4. /// [widget] properties, respectively, when the [initState] method is
  5. /// called.

框架调用[initState], [State]的子类应该重写[initState]以执行依赖于属性为[context]的[BuildContext]或属性为[widget]的小部件的做一次性初始化操作.
[State]的子类应重写[initState],以执行依赖于[BuildContext]或小部件的一次性初始化,在调用[initState]方法时,这些属性分别作为[context]和[widget]属性可用。

  1. /// * The framework calls [didChangeDependencies]. Subclasses of [State] should
  2. /// override [didChangeDependencies] to perform initialization involving
  3. /// [InheritedWidget]s. If [BuildContext.dependOnInheritedWidgetOfExactType] is
  4. /// called, the [didChangeDependencies] method will be called again if the
  5. /// inherited widgets subsequently change or if the widget moves in the tree.
  6. /// * At this point, the [State] object is fully initialized and the framework
  7. /// might call its [build] method any number of times to obtain a
  8. /// description of the user interface for this subtree. [State] objects can
  9. /// spontaneously request to rebuild their subtree by callings their
  10. /// [setState] method, which indicates that some of their internal state
  11. /// has changed in a way that might impact the user interface in this
  12. /// subtree.

框架调用[didChangeDependencies]。 [State]的子类应该重写[didChangeDependencies]用于执行[InheritedWidget]的初始化。如果[BuildContext.dependOnInheritedWidgetOfExactType] 已被调用,如果继承的小部件随后发生更改或小部件在树中移动,则会再次调用[didChangeDependencies]方法。
此时,[State]对象已完全初始化,框架可以多次调用它的[build]方法来获取此子树的用户界面描述, [State]对象可以通过调用其[setState]方法自发地请求重建其子树,这表明其某些内部状态已发生更改,可能会影响此子树中的用户界面。

  1. /// * During this time, a parent widget might rebuild and request that this
  2. /// location in the tree update to display a new widget with the same
  3. /// [runtimeType] and [Widget.key]. When this happens, the framework will
  4. /// update the [widget] property to refer to the new widget and then call the
  5. /// [didUpdateWidget] method with the previous widget as an argument. [State]
  6. /// objects should override [didUpdateWidget] to respond to changes in their
  7. /// associated widget (e.g., to start implicit animations). The framework
  8. /// always calls [build] after calling [didUpdateWidget], which means any
  9. /// calls to [setState] in [didUpdateWidget] are redundant.

在此期间,父部件可能会重建并请求更新树中的位置去显示一个新的有相同[runtimeType]和[Widget.key]的widget。当这种情况发生时,框架将更新[widget]属性以引用新的小部件,然后调用[didUpdateWidget]方法,并将前面的小部件作为参数。[State]对象应该重写[didUpdateWidget]以响应其关联小部件中的更改(例如,启动隐式动画)
框架总是在调用[didUpdateWidget]之后调用[build],这意味着在[didUpdateWidget]中调用[setState]是多余的。

  1. /// * During development, if a hot reload occurs (whether initiated from the
  2. /// command line `flutter` tool by pressing `r`, or from an IDE), the
  3. /// [reassemble] method is called. This provides an opportunity to
  4. /// reinitialize any data that was prepared in the [initState] method.

在开发过程中,如果发生热重载,就会调用了[reassemble]方法,这为重新初始化已在[initState]方法赋值的数据提供了修改的机会。

  1. /// * If the subtree containing the [State] object is removed from the tree
  2. /// (e.g., because the parent built a widget with a different [runtimeType]
  3. /// or [Widget.key]), the framework calls the [deactivate] method. Subclasses
  4. /// should override this method to clean up any links between this object
  5. /// and other elements in the tree (e.g. if you have provided an ancestor
  6. /// with a pointer to a descendant's [RenderObject]).

如果包含[State]对象的子树被从树中删除(例如,因为父级用不同的[runtimeType]或[Widget.key]),框架调用[deactivate]方法。子类应该重写此方法以清除此对象与树中其他元素之间的任何链接(例如,如果您为祖先提供了指向后代的[RenderObject]的指针)。

  1. /// * At this point, the framework might reinsert this subtree into another
  2. /// part of the tree. If that happens, the framework will ensure that it
  3. /// calls [build] to give the [State] object a chance to adapt to its new
  4. /// location in the tree. If the framework does reinsert this subtree, it
  5. /// will do so before the end of the animation frame in which the subtree was
  6. /// removed from the tree. For this reason, [State] objects can defer
  7. /// releasing most resources until the framework calls their [dispose]
  8. /// method.
  9. /// * If the framework does not reinsert this subtree by the end of the current
  10. /// animation frame, the framework will call [dispose], which indicates that
  11. /// this [State] object will never build again. Subclasses should override
  12. /// this method to release any resources retained by this object (e.g.,
  13. /// stop any active animations).
  14. /// * After the framework calls [dispose], the [State] object is considered
  15. /// unmounted and the [mounted] property is false. It is an error to call
  16. /// [setState] at this point. This stage of the lifecycle is terminal: there
  17. /// is no way to remount a [State] object that has been disposed.

此时,框架可能会将此子树重新插入到树的另一部分。如果发生这种情况,框架将确保调用[build],给[State]对象一个机会去适配其在树中的新位置。如果框架确实重新插入此子树,它将在从树中删除子树的动画帧结束之前执行此操作。因此,[State]对象可以推迟释放大多数资源,直到框架调用它们的[dispose]方法。
如果框架在当前动画帧结束时没有重新插入此子树,则框架将调用[dispose],这表示此[State]对象将不再生成。子类应重写此方法以释放此对象保留的任何资源(例如,停止任何活动动画)。
在框架调用[dispose]之后,将考虑[State]对象unmounted和[mounted]属性为false。你不应该在此时调用[setState]方法。这一阶段是生命周期的终点:无法重新装载已被释放的[State]对象。

StatefulWidget 生命周期如下图所示:
image.png

State中有两个常用属性:

  1. widget,它表示与该State实例关联的widget实例,由Flutter framework动态设置。注意,这种关联并非永久的,因为在应用生命周期中,UI树上的某一个节点的widget实例在重新构建时可能会变化,但State实例只会在第一次插入到树中时被创建,当在重新构建时,如果widget被修改了,Flutter framework会动态设置State.widget为新的widget实例。
  2. context。StatefulWidget对应的BuildContext,作用同StatelessWidget的BuildContext。

下面我们来看看各个回调函数:

  • initState(): 当 widget 第一次插入到 widget 树时会被调用,对于每一个State对象,Flutter 框架只会调用一次该回调,所以,通常在该回调中做一些一次性的操作(此时可使用依赖于属性为[context]的[BuildContext]或属性为[widget]的小部件),如状态初始化、订阅子树的事件通知等。不能在该回调中调用BuildContext.dependOnInheritedWidgetOfExactType(该方法用于在 widget 树上获取离当前 widget 最近的一个父级InheritedWidget),原因是在初始化完成后, widget 树中的InheritFrom widget也可能会发生变化,所以正确的做法应该在在build()方法或didChangeDependencies()中调用它。

  • didChangeDependencies():当State对象的依赖发生变化时会被调用;例如:在之前build() 中包含了一个InheritedWidget,然后在之后的build() 中Inherited widget发生了变化,那么此时Inherited widget的子 widget 的didChangeDependencies()回调都会被调用。典型的场景是当系统语言 Locale 或应用主题改变时,Flutter 框架会通知 widget 调用此回调。

  • build():此回调主要是用于构建 widget 子树的,会在如下场景被调用:

    1. 在调用initState()之后。
    2. 在调用didUpdateWidget()之后。
    3. 在调用setState()之后。
    4. 在调用didChangeDependencies()之后。
    5. 在State对象从树中一个位置移除后(会调用deactivate)又重新插入到树的其它位置之后。
  • reassemble():此回调是专门为了开发调试而提供的,在热重载(hot reload)时会被调用,此回调在Release模式下永远不会被调用。

  • didUpdateWidget():在 widget 重新构建时,Flutter 框架会调用widget.canUpdate来检测 widget 树中同一位置的新旧节点,然后决定是否需要更新,如果widget.canUpdate返回true则会调用此回调。正如之前所述,widget.canUpdate会在新旧 widget 的 key 和 runtimeType 同时相等时会返回true,也就是说在在新旧 widget 的key和runtimeType同时相等时didUpdateWidget()就会被调用。

    1. 只要在父widget中调用setState,子widget的didUpdateWidget就一定会被调用,不管父widget传递给子widget构造方法的参数有没有改变。
    2. 只要didUpdateWidget被调用,接来下build方法就一定会被调用。
  • deactivate():当 State 对象从树中被移除时,会调用此回调。在一些场景下,Flutter 框架会将 State 对象重新插到树中,如包含此 State 对象的子树在树的一个位置移动到另一个位置时(可以通过GlobalKey 来实现)。如果移除后没有重新插入到树中则紧接着会调用dispose()方法。

  • dispose():当 State 对象从树中被永久移除时调用;通常在此回调中释放资源。

build 方法在 State 中

为什么build()方法放在State(而不是StatefulWidget)中 ?这主要是为了提高开发的灵活性。如果将build()方法在StatefulWidget中则会有两个问题:

  • 状态访问不便

试想一下,如果我们的StatefulWidget有很多状态,而每次状态改变都要调用build方法,由于状态是保存在State中的,如果build方法在StatefulWidget中,那么build方法和状态分别在两个类中,那么构建时读取状态将会很不方便!试想一下,如果真的将build方法放在StatefulWidget中的话,由于构建用户界面过程需要依赖State,所以build方法将必须加一个State参数,大概是下面这样:

  1. widget build(BuildContext context, State state){
  2. //state.counter
  3. ...
  4. }

这样的话就只能将State的所有状态声明为公开的状态,这样才能在State类外部访问状态!但是,将状态设置为公开后,状态将不再具有私密性,这就会导致对状态的修改将会变的不可控。但如果将build()方法放在State中的话,构建过程不仅可以直接访问状态,而且也无需公开私有状态,这会非常方便。

  • 继承StatefulWidget不便

例如,Flutter中有一个动画 widget 的基类 AnimatedWidget,它继承自StatefulWidget类。AnimatedWidget中引入了一个抽象方法build(BuildContext context),继承自AnimatedWidget的动画 widget 都要实现这个build方法。现在设想一下,如果StatefulWidget 类中已经有了一个build方法,正如上面所述,此时build方法需要接收一个state对象,这就意味着AnimatedWidget必须将自己的State对象(记为_animatedWidgetState)提供给其子类,因为子类需要在其build方法中调用父类的build方法,代码可能如下:

  1. class MyAnimationWidget extends AnimatedWidget {
  2. @override
  3. Widget build(BuildContext context, State state){
  4. //由于子类要用到AnimatedWidget 的状态对象_animatedWidgetState,
  5. //所以AnimatedWidget 必须通过某种方式将其状态对象_animatedWidgetState
  6. //暴露给其子类
  7. super.build(context, _animatedWidgetState)
  8. }
  9. }

这样很显然是不合理的,因为

  1. AnimatedWidget的状态对象是AnimatedWidget内部实现细节,不应该暴露给外部。
  2. 如果要将父类状态暴露给子类,那么必须得有一种传递机制,而做这一套传递机制是无意义的,因为父子类之间状态的传递和子类本身逻辑是无关的。

综上所述,可以发现,对于StatefulWidget,将build方法放在State中,可以给开发带来很大的灵活性。

在 widget 树中获取State对象

由于 StatefulWidget 的的具体逻辑都在其 State 中,所以很多时候,我们需要获取 StatefulWidget 对应的State 对象来调用一些方法,比如Scaffold组件对应的状态类ScaffoldState中就定义了打开 SnackBar(路由页底部提示条)的方法。我们有两种方法在子 widget 树中获取父级 StatefulWidget 的State 对象。

  • 通过Context获取

context对象有一个findAncestorStateOfType()方法,该方法可以从当前节点沿着 widget 树向上查找指定类型的 StatefulWidget 对应的 State 对象。下面是实现打开 SnackBar 的示例:

  1. class GetStateObjectRoute extends StatefulWidget {
  2. const GetStateObjectRoute({Key? key}) : super(key: key);
  3. @override
  4. State<GetStateObjectRoute> createState() => _GetStateObjectRouteState();
  5. }
  6. class _GetStateObjectRouteState extends State<GetStateObjectRoute> {
  7. @override
  8. Widget build(BuildContext context) {
  9. return Scaffold(
  10. appBar: AppBar(
  11. title: Text("子树中获取State对象"),
  12. ),
  13. body: Center(
  14. child: Column(
  15. children: [
  16. Builder(builder: (context) {
  17. return ElevatedButton(
  18. onPressed: () {
  19. // 查找父级最近的Scaffold对应的ScaffoldState对象
  20. ScaffoldState _state = context.findAncestorStateOfType<ScaffoldState>()!;
  21. // 打开抽屉菜单
  22. _state.openDrawer();
  23. },
  24. child: Text('打开抽屉菜单1'),
  25. );
  26. }),
  27. ],
  28. ),
  29. ),
  30. drawer: Drawer(),
  31. );
  32. }
  33. }

一般来说,如果 StatefulWidget 的状态是私有的(不应该向外部暴露),那么我们代码中就不应该去直接获取其 State 对象;如果StatefulWidget的状态是希望暴露出的(通常还有一些组件的操作方法),我们则可以去直接获取其State对象。但是通过 context.findAncestorStateOfType 获取 StatefulWidget 的状态的方法是通用的,我们并不能在语法层面指定 StatefulWidget 的状态是否私有,所以在 Flutter 开发中便有了一个默认的约定:如果 StatefulWidget 的状态是希望暴露出的,应当在 StatefulWidget 中提供一个of 静态方法来获取其 State 对象,开发者便可直接通过该方法来获取;如果 State不希望暴露,则不提供of方法。这个约定在 Flutter SDK 里随处可见。所以,上面示例中的Scaffold也提供了一个of方法,我们其实是可以直接调用它的:

  1. Builder(builder: (context) {
  2. return ElevatedButton(
  3. onPressed: () {
  4. // 直接通过of静态方法来获取ScaffoldState
  5. ScaffoldState _state=Scaffold.of(context);
  6. // 打开抽屉菜单
  7. _state.openDrawer();
  8. },
  9. child: Text('打开抽屉菜单2'),
  10. );
  11. }),

又比如我们想显示 snack bar 的话可以通过下面代码调用:

  1. Builder(builder: (context) {
  2. return ElevatedButton(
  3. onPressed: () {
  4. ScaffoldMessenger.of(context).showSnackBar(
  5. SnackBar(content: Text("我是SnackBar")),
  6. );
  7. },
  8. child: Text('显示SnackBar'),
  9. );
  10. }),
  • GlobalKey

Flutter还有一种通用的获取State对象的方法——通过GlobalKey来获取,步骤分两步:

  1. 给目标StatefulWidget添加GlobalKey。

    1. //定义一个globalKey, 由于GlobalKey要保持全局唯一性,我们使用静态变量存储
    2. static GlobalKey<ScaffoldState> _globalKey= GlobalKey();
    3. ...
    4. Scaffold(
    5. key: _globalKey , //设置key
    6. ...
    7. )
  2. 通过GlobalKey来获取State对象

    1. _globalKey.currentState.openDrawer()

    GlobalKey 是 Flutter 提供的一种在整个 App 中引用 element 的机制。如果一个 widget 设置了GlobalKey,那么我们便可以通过globalKey.currentWidget获得该 widget 对象、globalKey.currentElement来获得 widget 对应的element对象,如果当前 widget 是StatefulWidget,则可以通过globalKey.currentState来获得该 widget 对应的state对象。

注意:使用 GlobalKey 开销较大,如果有其他可选方案,应尽量避免使用它。另外,同一个 GlobalKey 在整个 widget 树中必须是唯一的,不能重复。

参考资料

  1. Widget简介)