【发布时间】:2019-08-30 18:01:15
【问题描述】:
我只需要一些关于在调用 setState() 时颤振有状态小部件如何构建有状态子级的想法。请看下面的代码。
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 时,
输出 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
这里有什么区别?引擎盖下会发生什么?非常感谢详细的解释。
【问题讨论】: