[Flutter/dart]createState() and initState() are not called when a StatefulWidget is rebuilt from its
- M.R

- Dec 30, 2022
- 1 min read
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"
...






Comments