top of page

[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 All

Comments


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page