[Flutter/dart]createState() and initState() are not called when a StatefulWidget is rebuilt from its
Oveview
There is a generic StatefulWidget like below.
class childWidget extends StatefulWidget{
State<StatefulWidget> createState() {
return childWidgetState();
}
}
class childWidgetState extends State<childWidget>{
Widget build(BuildContext context) {
//・・・
}
void initState() {
//・・・
}
}
When this childWidget is rebuilt from the parent Widget, I expected initState() to run, but it seems that it runs only the first time.
Cause
I didn't understand that the Widget tree and the Element tree are two different things.
Flutter manages screen drawing information with 3 elements: Widget, Element, and RenderObject.
These are explained on various sites, so I will omit it here.
Briefly, when rebuilding
Widget is regenerated
Elements are reused
and
createState() and initState() are functions called when Element is created
With that in mind, you can see why.
That is, even if the parent is rebuilt, the existing Element will be used, so createState() and initState() will not be called.
Lastly
I misunderstood that "initState() should be called because I created a new Widget"
...
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments