老孟导读:此篇文章是生命周期相关文章的番外篇,在查看源码的过程当中发现了这一有趣的问题,欢迎你们一块儿探讨。html
Flutter 中Stateful 组件的生命周期:http://laomengit.com/blog/20201227/Stateful%E7%BB%84%E4%BB%B6%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.htmlgit
Flutter 中与平台相关的生命周期:http://laomengit.com/blog/20201227/%E7%9B%B8%E5%85%B3%E5%B9%B3%E5%8F%B0%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.html微信
博客中还有更多精彩文章,也欢迎加入 Flutter 交流群。闭包
将 build 方法放在 State 中比放在 StatefulWidget 中更具灵活性,好比说,AnimatedWidget 是 StatefulWidget 的子类,AnimatedWidget 是一个抽象类,其中有一个 Widget build(BuildContext context)
的抽象方法,此方法须要子类重写,AnimatedWidget 源代码以下:框架
abstract class AnimatedWidget extends StatefulWidget { ... /// Override this method to build widgets that depend on the state of the /// listenable (e.g., the current value of the animation). @protected Widget build(BuildContext context); /// Subclasses typically do not override this method. @override _AnimatedState createState() => _AnimatedState(); ... }
删除了一些代码,保留了重点代码。ide
试想一下,若是 build 方法放在 StatefulWidget 中,则 AnimatedWidget 中的 build 方法须要带一个 State 参数,以下:性能
abstract class AnimatedWidget extends StatefulWidget { ... /// Override this method to build widgets that depend on the state of the /// listenable (e.g., the current value of the animation). @protected Widget build(BuildContext context, AnimatedState state); /// Subclasses typically do not override this method. @override _AnimatedState createState() => _AnimatedState(); ... }
但 AnimatedState 是内部实现,并不须要开放给外部(开发者),外部也不须要知道 AnimatedState 的内部实现。动画
假设 build 方法在 StatefulWidget 中,StatefulWidget 的子类写法以下:ui
class MyWidget extends StatefulWidget { final Color color; @override Widget build(BuildContext context, MyWidgetState state) { print('${this.color}'); return Container(); } }
此时的 this 指向的是 MyWidget 的实例,而后父组件改变颜色,从新构建 MyWidget 组件,前一个 MyWidget 的实例中的 this 依然指向前一个 MyWidget 的实例,颜色并未发生变化。this
若是 build 方法在 State 中,代码以下:
class MyWidget extends StatefulWidget { final Color color; const MyWidget({Key key, this.color}) : super(key: key); @override _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { @override Widget build(BuildContext context) { print('${widget.color}'); return Container(); } }
一样,父组件改变颜色,从新构建 MyWidget 组件,此时框架更新了 State 对象的 widget 属性的引用,新的 MyWidget 实例和 $ {widget.color} 将显示绿色。
有状态的组件包含StatefulWidget 和 State,当有状态组件的配置发生更改时,StatefulWidget 将会被丢弃并重建,而 State 不会重建,框架会更新 State 对象中 widget 的引用,这极大的减轻了系统重建有状态组件的工做。
此方式对动画来讲极为重要,因为 State 不会被重建,保留了前面的状态,不断的根据前一个状态计算下一个状态并重建其widget,达到动画的效果。
老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com
欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:
![]() |
![]() |