I am confused about when to put my code in initState()
compared to build()
in a stateful widget. I am doing a quiz on flutter's udacity course which has this todo item, which was to move a block of code from build()
to initState()
. But I don't know the purpose or advantage of doing that. Why not just put all the code in build()
?
Is it that build()
is called only once while initState()
is called on every state change?
Thank you.
The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets.
initState() This is the first method called when the widget is created (after the class constructor, of course.) initState is called once and only once. It must also call super.
Why is the build method on State, and not StatefulWidget? Putting a Widget build(BuildContext context) method on State rather than putting a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when subclassing StatefulWidget.
super. initState() forwards to the default implementation of the State<T> base class of your widget. If you don't override, the default implementation will not be executed but the widget depends on that to work properly.
This is actually the opposite.
build
can be called again in many situations. Such as state change or parent rebuild.
While initState
is called only one time.
build
should be used only for layout. While initState
is usually used for variable initialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With