Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter initState() vs build()?

Tags:

state

flutter

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.

like image 717
AskYous Avatar asked Aug 16 '18 00:08

AskYous


People also ask

What is initState () in flutter?

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.

Is initState called before build?

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 stateful widget?

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.

What is the use of super initState?

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.


1 Answers

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.

like image 198
Rémi Rousselet Avatar answered Oct 13 '22 12:10

Rémi Rousselet