setState()如何重建子窗口小部件? [英] How does setState() rebuild child widgets?

查看:80
本文介绍了setState()如何重建子窗口小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要了解在调用setState()时,抖动的有状态小部件如何构建其有状态的子级。请查看下面的代码。

I just need some idea on how flutter stateful widgets build their stateful children when setState() is invoked. Please look at the code below.

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Widget build(BuildContext context) {
    print("Parent build method invoked");
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            StatefulChild(), // Keeping this line gives the output 1
            statefulChild, // Keeping this line gives the output 2
            RaisedButton(
              child: Text('Click me'),
              onPressed: () {
                setState(() {});
              },
            )
          ],
        ),
      ),
    );
  }

  StatefulChild statefulChild = StatefulChild();
}

class StatefulChild extends StatefulWidget {
  StatefulChildState createState() => StatefulChildState();
}

class StatefulChildState extends State<StatefulChild> {
  @override
  Widget build(BuildContext context) {
    print("Child00 build method invoked");
    return Container();
  }
}

按下RaisedButton时,

When the RaisedButton is pressed,

输出1 //仅保留 StatefulChild()

I/flutter ( 2903): Parent build method invoked
I/flutter ( 2903): Child00 build method invoked

输出2 //仅保留 statefulChild

I/flutter ( 2903): Parent build method invoked

什么是这里有区别吗?引擎盖下会发生什么?

What is the difference here? What happens under the hood? Detailed explanation is much appreciated.

推荐答案

重建小部件树时,Flutter使用 == build 方法返回的先前和新的小部件。

When the widget tree rebuilds, Flutter compares using == the previous and new widget returned by the build method.

其中有两种情况情况:


  • == false 。在这种情况下,Flutter将比较 runtimeType & 来了解是否应保留前一个小部件的状态。然后Flutter在该小部件上调用 build

  • == is false. In that case, Flutter will compare the runtimeType & key to know if the state of the previous widget should be preserved. Then Flutter calls build on that widget

== true 。在这种情况下,Flutter中止了窗口小部件树的构建(也称为 build )。

== is true. In which case, Flutter aborts the building of the widget tree (aka won't call build).

由于小部件的不可变性,因此可以进行优化。

This is an optimization possible thanks to the immutability of widgets.

由于小部件是不可变的,如果 == 尚未更改,则意味着没有任何更新。因此Flutter可以安全地对其进行优化。

Since widgets are immutable, if == haven't changed then it means that there's nothing to update. Flutter can therefore safely optimize that.

这篇关于setState()如何重建子窗口小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆