What is the difference between initState and a class constructor in Flutter?
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.
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