Reputation: 5543
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.
Upvotes: 47
Views: 14087
Reputation: 44861
The difference is (in the context of creating a State
object) which has the initState()
method:
constructor
simply create a newState
instance
initState()
is called after the object is created and at this point you have access to theBuildContext
or theStatefulWidget
to which theState
is attached to, respectively using thecontext
and thewidget
properties. At this point theState
is already mounted.
Reference State
: https://api.flutter.dev/flutter/widgets/State-class.html
Reference mounted State
: https://api.flutter.dev/flutter/widgets/State/mounted.html
Upvotes: 49
Reputation: 103531
In some cases you will need to start an animation or change the state when you create your Widget
, then is not possible to do that in your constructor because your Widget
is not inserted in the tree yet.
Example of AnimationController
AnimationController _animationController ;
...
@override
void initState() {
... instance the animationController
_animationController.forward();
super.initState();
}
Another example, when you receive some params from another Widget
, let say your StatefulWidget
has a param named title
and you want to create a local variable in your State class to handle the state, you will have to do something like this:
class ExampleWidget extends StatefulWidget {
final String title;
ExampleWidget({this.title});
....
YourStateClass extends State<ExampleWidget> {
var localVariable;
@override
void initState() {
localVariable = widget.title;
super.initState();
}
And now you could use your localVariable
inside your widget tree to update the state.
Upvotes: 17
Reputation: 1857
constructor is used to create an instance(object).
initstate is used to initalize the contents of an already existing object.
For example,
Suppose you open an app having multiple routes / pages. When u open any particular page then an object A of its contents is created (with some initial data) which u see on screen.
Now suppose u press a button (which performs a specific task that changes the data) on that particular page. Then initstate will be called to initalize the data of object A without having u to open the app again from fresh.
Also, it must be noted that initstate is called before build and no context is available at that moment.
Thats all.
Upvotes: 3