Flutter-为什么在每次重新构建父窗口小部件时都未调用子窗口小部件的initState()? [英] Flutter - Why is child widget's initState() is not called on every rebuild of Parent widget?
问题描述
我有一个 Parent
小部件,它具有某种状态,在这种情况下为计数器.
I have a Parent
widget, which holds some state, a counter in this case.
此状态通过其构造函数传递给 Child
小部件.
This state is passed on to a Child
widget using its constructor.
现在,据我所知, Child
应该在每次 Parent
状态更改时重新构建,因为它位于 build()内部
父母的函数,并且每次状态更改时都会调用 build()
.
Now, how I understand it, the Child
should get re-built every-time Parent
's state changes, since it's inside the build()
function of Parent
, and build()
gets called every-time the state changes.
这个概念使我相信,每次计数器更改时,都会输出 INIT STATE!
消息.事实并非如此!
This concept lead me to believe that the INIT STATE!
message would be printed every time the counter changes. But it is not the case!
我本质上希望每当 Child
的构造函数参数( message
)更改时,都将仅触发一次钩子".
I essentially want a "hook" that gets fired only once, whenever the Child
's constructor arguments (message
) change.
有人可以解释为什么会这样吗,以及使用上述挂钩"的正确方法是什么?
Can someone please explain why this is the case, and what is the right way to have the aforementioned "hook"?
class Child extends StatefulWidget {
final String message;
const Child(this.message, {Key key}) : super(key: key);
@override
_ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
@override
void initState() {
print("INIT STATE!");
super.initState();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(widget.message),
);
}
}
class Parent extends StatefulWidget {
@override
_ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int _counter = 0;
@override
void initState() {
Timer.periodic(Duration(seconds: 1), (_) {
if (mounted) {
setState(() {
_counter += 1;
});
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Child(_counter.toString());
}
}
推荐答案
Ok, looks like this was clearly mentioned in the State class' docs.
正确的方法是重写 State
子类中的 didUpdateWidget
方法.
The correct way to do this is to override the didUpdateWidget
method in the State
subclass.
这篇关于Flutter-为什么在每次重新构建父窗口小部件时都未调用子窗口小部件的initState()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!