Android – the difference between initState and a class constructor in Flutter

androidflutterios

I read the documentation but it is not clear.

It states "[initState is] Called when this object is inserted into the tree."

When a widget is inserted into a tree, it means it has been created, which means the class constructor is called. What is the purpose of init? Isn't the constructor's purpose to initialize the class instance?

Thank you guys for your time.

Best Answer

The difference is (in the context of creating a State object) which has the initState() method:

  • constructor simply create a new State instance

  • initState() is called after the object is created and at this point you have access to the BuildContext or the StatefulWidget to which the State is attached to, respectively using the context and the widget properties. At this point the State is already mounted.

Reference State: https://docs.flutter.io/flutter/widgets/State-class.html

Reference mounted State: https://docs.flutter.io/flutter/widgets/State/mounted.html