关于flutter:老孟Flutter为什么-build-方法放在-State-中而不是在-StatefulWidget-中

1次阅读

共计 2343 个字符,预计需要花费 6 分钟才能阅读完成。

老孟导读 :此篇文章是 生命周期相干文章 的番外篇,在查看源码的过程中发现了这一乏味的问题,欢送大家一起探讨。

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.html

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 中更具灵活性,比如说,AnimatedWidgetStatefulWidget 的子类,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();

  ...
}

删除了一些代码,保留了重点代码。

试想一下,如果 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 的外部实现。

闭包 this 指向异样

假如 build 办法在 StatefulWidget 中,StatefulWidget 的子类写法如下:

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 的实例,色彩并未发生变化。

如果 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

增加微信或者公众号支付《330 个控件大全》和《Flutter 实战》PDF。

欢送退出 Flutter 交换群(微信:laomengit)、关注公众号【老孟 Flutter】:

正文完
 0