Widget类本身是一个抽象类,其中最核心的就是定义了createElement()接口,在 Flutter 开发中,我们一般都不用直接继承Widget类来实现一个新组件,相反,我们通常会通过继承StatelessWidget或StatefulWidget来间接继承widget类来实现。StatelessWidget和StatefulWidget都是直接继承自Widget类,而这两个类也正是 Flutter 中非常重要的两个抽象类,它们引入了两种 widget 模型,接下来我们将重点介绍一下这两个类。
一. StatelessWidget
StatelessWidget相对比较简单,它继承自Widget类,重写了createElement()方法:
@overrideStatelessElement 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。我们看一个简单的例子:
class Frog extends StatelessWidget {const Frog({Key key,this.color = const Color(0xFF2DBD3A),this.child,}) : super(key: key);final Color color;final Widget child;@overrideWidget build(BuildContext context) {return Container(color: color, child: child);}}
上面的代码,实现了一个Frog widget。
按照惯例,widget 的构造函数参数应使用命名参数,命名参数中的必要参数要添加 @required 标注,这样有利于静态代码分析器进行检查。另外,在继承 widget 时,第一个参数通常应该是 Key,另外,如果 Widget 需要接收子 Widget,那么 child 或 children 参数通常应被放在参数列表的最后。同样是按照惯例,Widget的属性应尽可能的被声明为 final,防止被意外改变。
然后我们可以通过如下方式使用它:
Widget build(BuildContext context) {return Frog(color: Color(0xFF2DAA3A));}

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
constwidgets where possible, and provide aconstconstructor 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的类定义:
abstract class StatefulWidget extends Widget {const StatefulWidget({ Key key }) : super(key: key);@overrideStatefulElement createElement() => new StatefulElement(this);@protectedState createState();}
- StatefulElement 间接继承自 Element 类,与 StatefulWidget 相对应(作为其配置数据)。StatefulElement 中可能会多次调用 createState() 来创建状态(State)对象。
- createState() 用于创建和 StatefulWidget 相关的状态,它在 StatefulWidget 的生命周期中可能会被多次调用。例如,当一个 StatefulWidget 同时插入到 widget 树的多个位置时,Flutter framework 就会调用该方法为每一个位置生成一个独立的 State 实例,其实,本质上就是一个 StatefulElement 对应一个State实例。
接下来我们按照文档一部分一部分的看,部分与 StatelessWidget 相同的文档将不在展示.
/// A widget that has mutable state.////// State is information that (1) can be read synchronously when the widget is/// built and (2) might change during the lifetime of the widget. It is the/// responsibility of the widget implementer to ensure that the [State] is/// promptly notified when such state changes, using [State.setState]./// A stateful 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).////// Stateful widgets are useful when the part of the user interface you are/// describing can change dynamically, e.g. due to having an internal/// clock-driven state, or depending on some system state. For compositions that/// depend only on the configuration information in the object itself and the/// [BuildContext] in which the widget is inflated, consider using/// [StatelessWidget].
具有可变state的widget,state是(1)在小部件构建时可以同步读取的信息,以及(2)在小部件的生存期内可能更改的信息。widget 实现者有责任确保在状态发生变化时及时通知[State],使用[State.setState].
StatefulWidget是通过构建一组其他小部件来描述用户界面的一部分的 widget,在递归性的构建过程中直到用户界面的描述完全具体化 (例如,完全由[RenderObjectWidget]s组成,描述具体的[RenderObject]s)。
当你描述的部分用户界面可以动态改变时,有状态小部件是很有用的,例如由于有一个内部时钟驱动的状态,或者取决于某些系统状态。对于只依赖于对象本身的配置信息和小部件膨胀成的[BuildContext],考虑使用[StatelessWidget].
/// [StatefulWidget] instances themselves are immutable and store their mutable/// state either in separate [State] objects that are created by the/// [createState] method, or in objects to which that [State] subscribes, for/// example [Stream] or [ChangeNotifier] objects, to which references are stored/// in final fields on the [StatefulWidget] itself.////// The framework calls [createState] whenever it inflates a/// [StatefulWidget], which means that multiple [State] objects might be/// associated with the same [StatefulWidget] if that widget has been inserted/// into the tree in multiple places. Similarly, if a [StatefulWidget] is/// removed from the tree and later inserted in to the tree again, the framework/// will call [createState] again to create a fresh [State] object, simplifying/// the lifecycle of [State] objects.
[StatefulWidget]实例本身是不可变的, 它们的可变状态存储在由[createState]方法创建的单独的[state]对象中,
或者存储在该[state]订阅的对象中,例如[Stream]或[ChangeNotifier]对象,其引用存储在[StatefulWidget]本身的最终字段中。
框架在 inflates [StatefulWidget]时调用[createState],这意味着如果多个[State]对象被插入到树的多个位置,那么多个[State]对象可能与同一个[StatefulWidget]相关联。
类似地,如果一个[StatefulWidget]从树中删除,然后再次插入到树中,框架将再次调用[createState]来创建一个新的[State]对象,从而简化[State]对象的生命周期。
/// A [StatefulWidget] keeps the same [State] object when moving from one/// location in the tree to another if its creator used a [GlobalKey] for its/// [key]. Because a widget with a [GlobalKey] can be used in at most one/// location in the tree, a widget that uses a [GlobalKey] has at most one/// associated element. The framework takes advantage of this property when/// moving a widget with a global key from one location in the tree to another/// by grafting the (unique) subtree associated with that widget from the old/// location to the new location (instead of recreating the subtree at the new/// location). The [State] objects associated with [StatefulWidget] are grafted/// along with the rest of the subtree, which means the [State] object is reused/// (instead of being recreated) in the new location. However, in order to be/// eligible for grafting, the widget must be inserted into the new location in/// the same animation frame in which it was removed from the old location.
[StatefulWidget]将保持相同的[State]对象当它的创建者使用[GlobalKey]作为它的[key],从树中的一个位置移动到另一个位置时。 因为带有[GlobalKey]的widget最多只能在树中的一个位置使用,带[GlobalKey]的小部件最多有一个关联element。框架通过使用该属性,当将具有全局键的小部件从树中的一个位置移动到另一个位置时,框架会将与该小部件关联的(唯一的)子树从旧位置移植到新位置(而不是在新位置重新创建子树),与[StatefulWidget]关联的[State]对象与子树的其余部分一起被嫁接,这意味着[State]对象在新位置被重用(而不是被重新创建)。
但是,为了符合移植的条件,小部件必须在同一画帧中从旧位置移除并插入到新位置。
/// There are two primary categories of [StatefulWidget]s.////// The first is one which allocates resources in [State.initState] and disposes/// of them in [State.dispose], but which does not depend on [InheritedWidget]s/// or call [State.setState]. Such widgets are commonly used at the root of an/// application or page, and communicate with subwidgets via [ChangeNotifier]s,/// [Stream]s, or other such objects. Stateful widgets following such a pattern/// are relatively cheap (in terms of CPU and GPU cycles), because they are/// built once then never update. They can, therefore, have somewhat complicated/// and deep build methods.////// The second category is widgets that use [State.setState] or depend on/// [InheritedWidget]s. These will typically rebuild many times during the/// application's lifetime, and it is therefore important to minimize the impact/// of rebuilding such a widget. (They may also use [State.initState] or/// [State.didChangeDependencies] and allocate resources, but the important part/// 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]分配资源,但重要的部分是它们的重建。)
性能优化影响
/// There are several techniques one can use to minimize the impact of/// rebuilding a stateful widget:////// * Push the state to the leaves. For example, if your page has a ticking/// clock, rather than putting the state at the top of the page and/// rebuilding the entire page each time the clock ticks, create a dedicated/// clock widget that only updates itself.////// * Minimize the number of nodes transitively created by the build method and/// any widgets it creates. Ideally, a stateful widget would only create a/// single widget, and that widget would be a [RenderObjectWidget]./// (Obviously this isn't always practical, but the closer a widget gets to/// this ideal, the more efficient it will be.)////// * If a subtree does not change, cache the widget that represents that/// subtree and re-use it each time it can be used. It is massively more/// efficient for a widget to be re-used than for a new (but/// identically-configured) widget to be created. Factoring out the stateful/// part into a widget that takes a child argument is a common way of doing/// this.////// * Use `const` widgets where possible. (This is equivalent to caching a/// widget and re-using it.)////// * Avoid changing the depth of any created subtrees or changing the type of/// any widgets in the subtree. For example, rather than returning either the/// child or the child wrapped in an [IgnorePointer], always wrap the child/// widget in an [IgnorePointer] and control the [IgnorePointer.ignoring]/// property. This is because changing the depth of the subtree requires/// rebuilding, laying out, and painting the entire subtree, whereas just/// changing the property will require the least possible change to the/// render tree (in the case of [IgnorePointer], for example, no layout or/// repaint is necessary at all).////// * If the depth must be changed for some reason, consider wrapping the/// common parts of the subtrees in widgets that have a [GlobalKey] that/// remains consistent for the life of the stateful widget. (The/// [KeyedSubtree] widget may be useful for this purpose if no other widget/// can conveniently be assigned the key.)
有几种方法可用于最小化重新构建SataelessWidget的影响:
- 把 state 放到页节点上。例如,如果您的页面有一个滴答作响的时钟,与其将 state 放在页面顶部,每次在时钟滴答作响时重建整个页面,不如创建一个只更新自身的专用时钟小部件。
- 最小化由build方法及其创建的任何小部件以传递方式创建的节点数。理想情况下,一个有状态的小部件将只创建一个小部件,而该小部件将是一个[RenderObjectWidget]。(显然这并不总是可行的,但是小部件越接近这个理想状况,它的效率就越高。)
- 如果子树没有改变,缓存该组件表示该小部件可以在每次可以使用它时重新使用它;重新使用一个小部件比创建一个新的(但配置相同的)小部件要高效得多。将有状态部分分解成一个接受子参数的小部件是一种常见的方法。
- 尽可能使用“const”小部件。(这相当于缓存小部件并重新使用。)
避免更改任何已创建子树的深度或更改子树中任何小部件的类型。例如,与其返回 child 或者被包裹在[IgnorePointer]中的子 child,不如始终用[IgnorePointer]包裹子部件并控制[IgnorePointer.ignoring]属性。这是因为更改子树的深度需要重建、布局和绘制整个子树,而仅更改属性就只需要对渲染树进行尽可能少的更改
(例如,在[IgnorePointer]的情况下,根本不需要重新布局或绘制)。
如果由于某种原因必须更改深度,请考虑将子树的公共部分包裹到具有在有状态小部件的生命周期内保持一致的[GlobalKey]的小部件中。(如果没有其他小部件可以方便地分配 key,[KeyedSubtree]小部件可以用于此目的。)
State
/// The logic and internal state for a [StatefulWidget].////// State is information that (1) can be read synchronously when the widget is/// built and (2) might change during the lifetime of the widget. It is the/// responsibility of the widget implementer to ensure that the [State] is/// promptly notified when such state changes, using [State.setState].
由上面的文档可知: state 是 [StatefulWidget]的逻辑和内部状态,是(1)在小部件构建时可以同步读取的信息,以及(2)在小部件的生存期内可能更改的信息。Widget 实现者有责任确保在状态发生变化时及时通知[State],使用[State.setState]。一个 StatefulWidget 类会对应一个 State 类,State 表示与其对应的 StatefulWidget 要维护的状态,State 中的保存的状态信息可以:
- 在 widget 构建时可以被同步读取。
- 在 widget 生命周期中可以被改变,当 State 被改变时,可以手动调用其 setState() 方法通知 Flutter framework 状态发生改变,Flutter framework 在收到消息后,会重新调用其 build 方法重新构建 widget 树,从而达到更新UI的目的。
/// [State] objects are created by the framework by calling the/// [StatefulWidget.createState] method when inflating a [StatefulWidget] to/// insert it into the tree. Because a given [StatefulWidget] instance can be/// inflated multiple times (e.g., the widget is incorporated into the tree in/// multiple places at once), there might be more than one [State] object/// associated with a given [StatefulWidget] instance. Similarly, if a/// [StatefulWidget] is removed from the tree and later inserted in to the tree/// again, the framework will call [StatefulWidget.createState] again to create/// a fresh [State] object, simplifying the lifecycle of [State] objects.
当[StatefulWidget]被膨胀插入到树时,[State]对象由框架通过调用 [StatefulWidget.createState]方法创建。因为给定的[StatefulWidget]实例可以膨胀多次(例如,该小部件一次在多个位置合并到树中),所以可能有多个[State]对象与给定的[StatefulWidget]实例关联。类似地,如果[StatefulWidget]从树中移除,然后再次插入到树中,框架将调用[StatefulWidget.createState]再次创建一个新的[State]对象,简化[State]对象的生命周期。
State 状态
/// * The framework creates a [State] object by calling/// [StatefulWidget.createState]./// * The newly created [State] object is associated with a [BuildContext]./// This association is permanent: the [State] object will never change its/// [BuildContext]. However, the [BuildContext] itself can be moved around/// the tree along with its subtree. At this point, the [State] object is/// considered [mounted].
框架通过调用[StatefulWidget.createState]来创建[State]对象。
新创建的[State]对象与[BuildContext]关联,此关联是永久的,[State]对象永远不会更改其 [BuildContext]。但是,[BuildContext]本身可以在树及其子树周围移动。此时,[State]对象被认为是[mounted]。
/// * The framework calls [initState]. Subclasses of [State] should override/// [initState] to perform one-time initialization that depends on the/// [BuildContext] or the widget, which are available as the [context] and/// [widget] properties, respectively, when the [initState] method is/// called.
框架调用[initState], [State]的子类应该重写[initState]以执行依赖于属性为[context]的[BuildContext]或属性为[widget]的小部件的做一次性初始化操作.
[State]的子类应重写[initState],以执行依赖于[BuildContext]或小部件的一次性初始化,在调用[initState]方法时,这些属性分别作为[context]和[widget]属性可用。
/// * The framework calls [didChangeDependencies]. Subclasses of [State] should/// override [didChangeDependencies] to perform initialization involving/// [InheritedWidget]s. If [BuildContext.dependOnInheritedWidgetOfExactType] is/// called, the [didChangeDependencies] method will be called again if the/// inherited widgets subsequently change or if the widget moves in the tree./// * At this point, the [State] object is fully initialized and the framework/// might call its [build] method any number of times to obtain a/// description of the user interface for this subtree. [State] objects can/// spontaneously request to rebuild their subtree by callings their/// [setState] method, which indicates that some of their internal state/// has changed in a way that might impact the user interface in this/// subtree.
框架调用[didChangeDependencies]。 [State]的子类应该重写[didChangeDependencies]用于执行[InheritedWidget]的初始化。如果[BuildContext.dependOnInheritedWidgetOfExactType] 已被调用,如果继承的小部件随后发生更改或小部件在树中移动,则会再次调用[didChangeDependencies]方法。
此时,[State]对象已完全初始化,框架可以多次调用它的[build]方法来获取此子树的用户界面描述, [State]对象可以通过调用其[setState]方法自发地请求重建其子树,这表明其某些内部状态已发生更改,可能会影响此子树中的用户界面。
/// * During this time, a parent widget might rebuild and request that this/// location in the tree update to display a new widget with the same/// [runtimeType] and [Widget.key]. When this happens, the framework will/// update the [widget] property to refer to the new widget and then call the/// [didUpdateWidget] method with the previous widget as an argument. [State]/// objects should override [didUpdateWidget] to respond to changes in their/// associated widget (e.g., to start implicit animations). The framework/// always calls [build] after calling [didUpdateWidget], which means any/// calls to [setState] in [didUpdateWidget] are redundant.
在此期间,父部件可能会重建并请求更新树中的位置去显示一个新的有相同[runtimeType]和[Widget.key]的widget。当这种情况发生时,框架将更新[widget]属性以引用新的小部件,然后调用[didUpdateWidget]方法,并将前面的小部件作为参数。[State]对象应该重写[didUpdateWidget]以响应其关联小部件中的更改(例如,启动隐式动画)
框架总是在调用[didUpdateWidget]之后调用[build],这意味着在[didUpdateWidget]中调用[setState]是多余的。
/// * During development, if a hot reload occurs (whether initiated from the/// command line `flutter` tool by pressing `r`, or from an IDE), the/// [reassemble] method is called. This provides an opportunity to/// reinitialize any data that was prepared in the [initState] method.
在开发过程中,如果发生热重载,就会调用了[reassemble]方法,这为重新初始化已在[initState]方法赋值的数据提供了修改的机会。
/// * If the subtree containing the [State] object is removed from the tree/// (e.g., because the parent built a widget with a different [runtimeType]/// or [Widget.key]), the framework calls the [deactivate] method. Subclasses/// should override this method to clean up any links between this object/// and other elements in the tree (e.g. if you have provided an ancestor/// with a pointer to a descendant's [RenderObject]).
如果包含[State]对象的子树被从树中删除(例如,因为父级用不同的[runtimeType]或[Widget.key]),框架调用[deactivate]方法。子类应该重写此方法以清除此对象与树中其他元素之间的任何链接(例如,如果您为祖先提供了指向后代的[RenderObject]的指针)。
/// * At this point, the framework might reinsert this subtree into another/// part of the tree. If that happens, the framework will ensure that it/// calls [build] to give the [State] object a chance to adapt to its new/// location in the tree. If the framework does reinsert this subtree, it/// will do so before the end of the animation frame in which the subtree was/// removed from the tree. For this reason, [State] objects can defer/// releasing most resources until the framework calls their [dispose]/// method./// * If the framework does not reinsert this subtree by the end of the current/// animation frame, the framework will call [dispose], which indicates that/// this [State] object will never build again. Subclasses should override/// this method to release any resources retained by this object (e.g.,/// stop any active animations)./// * After the framework calls [dispose], the [State] object is considered/// unmounted and the [mounted] property is false. It is an error to call/// [setState] at this point. This stage of the lifecycle is terminal: there/// 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 生命周期如下图所示:
State中有两个常用属性:
- widget,它表示与该State实例关联的widget实例,由Flutter framework动态设置。注意,这种关联并非永久的,因为在应用生命周期中,UI树上的某一个节点的widget实例在重新构建时可能会变化,但State实例只会在第一次插入到树中时被创建,当在重新构建时,如果widget被修改了,Flutter framework会动态设置State.widget为新的widget实例。
- 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 子树的,会在如下场景被调用:
- 在调用initState()之后。
- 在调用didUpdateWidget()之后。
- 在调用setState()之后。
- 在调用didChangeDependencies()之后。
- 在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()就会被调用。
- 只要在父widget中调用setState,子widget的didUpdateWidget就一定会被调用,不管父widget传递给子widget构造方法的参数有没有改变。
- 只要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参数,大概是下面这样:
widget build(BuildContext context, State state){//state.counter...}
这样的话就只能将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方法,代码可能如下:
class MyAnimationWidget extends AnimatedWidget {@overrideWidget build(BuildContext context, State state){//由于子类要用到AnimatedWidget 的状态对象_animatedWidgetState,//所以AnimatedWidget 必须通过某种方式将其状态对象_animatedWidgetState//暴露给其子类super.build(context, _animatedWidgetState)}}
这样很显然是不合理的,因为
- AnimatedWidget的状态对象是AnimatedWidget内部实现细节,不应该暴露给外部。
- 如果要将父类状态暴露给子类,那么必须得有一种传递机制,而做这一套传递机制是无意义的,因为父子类之间状态的传递和子类本身逻辑是无关的。
综上所述,可以发现,对于StatefulWidget,将build方法放在State中,可以给开发带来很大的灵活性。
在 widget 树中获取State对象
由于 StatefulWidget 的的具体逻辑都在其 State 中,所以很多时候,我们需要获取 StatefulWidget 对应的State 对象来调用一些方法,比如Scaffold组件对应的状态类ScaffoldState中就定义了打开 SnackBar(路由页底部提示条)的方法。我们有两种方法在子 widget 树中获取父级 StatefulWidget 的State 对象。
- 通过Context获取
context对象有一个findAncestorStateOfType()方法,该方法可以从当前节点沿着 widget 树向上查找指定类型的 StatefulWidget 对应的 State 对象。下面是实现打开 SnackBar 的示例:
class GetStateObjectRoute extends StatefulWidget {const GetStateObjectRoute({Key? key}) : super(key: key);@overrideState<GetStateObjectRoute> createState() => _GetStateObjectRouteState();}class _GetStateObjectRouteState extends State<GetStateObjectRoute> {@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("子树中获取State对象"),),body: Center(child: Column(children: [Builder(builder: (context) {return ElevatedButton(onPressed: () {// 查找父级最近的Scaffold对应的ScaffoldState对象ScaffoldState _state = context.findAncestorStateOfType<ScaffoldState>()!;// 打开抽屉菜单_state.openDrawer();},child: Text('打开抽屉菜单1'),);}),],),),drawer: Drawer(),);}}
一般来说,如果 StatefulWidget 的状态是私有的(不应该向外部暴露),那么我们代码中就不应该去直接获取其 State 对象;如果StatefulWidget的状态是希望暴露出的(通常还有一些组件的操作方法),我们则可以去直接获取其State对象。但是通过 context.findAncestorStateOfType 获取 StatefulWidget 的状态的方法是通用的,我们并不能在语法层面指定 StatefulWidget 的状态是否私有,所以在 Flutter 开发中便有了一个默认的约定:如果 StatefulWidget 的状态是希望暴露出的,应当在 StatefulWidget 中提供一个of 静态方法来获取其 State 对象,开发者便可直接通过该方法来获取;如果 State不希望暴露,则不提供of方法。这个约定在 Flutter SDK 里随处可见。所以,上面示例中的Scaffold也提供了一个of方法,我们其实是可以直接调用它的:
Builder(builder: (context) {return ElevatedButton(onPressed: () {// 直接通过of静态方法来获取ScaffoldStateScaffoldState _state=Scaffold.of(context);// 打开抽屉菜单_state.openDrawer();},child: Text('打开抽屉菜单2'),);}),
又比如我们想显示 snack bar 的话可以通过下面代码调用:
Builder(builder: (context) {return ElevatedButton(onPressed: () {ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("我是SnackBar")),);},child: Text('显示SnackBar'),);}),
- GlobalKey
Flutter还有一种通用的获取State对象的方法——通过GlobalKey来获取,步骤分两步:
给目标StatefulWidget添加GlobalKey。
//定义一个globalKey, 由于GlobalKey要保持全局唯一性,我们使用静态变量存储static GlobalKey<ScaffoldState> _globalKey= GlobalKey();...Scaffold(key: _globalKey , //设置key...)
通过GlobalKey来获取State对象
_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 树中必须是唯一的,不能重复。
