setState() 如何重建子部件? [英] How does setState() rebuild child widgets?
问题描述
我只需要一些关于在调用 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()
,
Output 1 // Keeping only StatefulChild()
,
I/flutter ( 2903): Parent build method invoked
I/flutter ( 2903): Child00 build method invoked
输出 2//只保留 statefulChild
,
Output 2 // Keeping only statefulChild
,
I/flutter ( 2903): Parent build method invoked
这里有什么区别?引擎盖下会发生什么?非常感谢详细的解释.
What is the difference here? What happens under the hood? Detailed explanation is much appreciated.
推荐答案
当 widget 树重建时,Flutter 使用 ==
比较 build
方法.
When the widget tree rebuilds, Flutter compares using ==
the previous and new widget returned by the build
method.
这种情况有两种情况:
==
是false
.在这种情况下,Flutter 会比较runtimeType
和key
以了解是否应保留前一个小部件的状态.然后 Flutter 在该小部件上调用build
==
isfalse
. In that case, Flutter will compare theruntimeType
&key
to know if the state of the previous widget should be preserved. Then Flutter callsbuild
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屋!