Home > Net >  Flutter : InitState understanding
Flutter : InitState understanding

Time:06-24

I'm trying to understand why we have to use initState, I read a lot about it in internet but still can't realy understand the impact of it in the code.

I saw in a tutorial, in a form where we can add a new product (title, price, image....) the add this in the begining of the form, why this is important ? what gonna happen if it is not here ?

  void initState() {
    _imageUrlFocusNode.addListener(_updateImageUrl);
    super.initState();
  }

Thank you

CodePudding user response:

When a StatefulWidget is instanciated, it's state is not immediately available to be used and modified. The initState @override is used to run code that requires access to the state as soon as it is available.

On the example you use, it seems like it is adding a listener to be notified of changes on a focusNode of a form widget. Which will make changes to the state of your current StatefulWidget. Hence why it needs to be added on this initState override.

CodePudding user response:

Called when this object is inserted into the tree. The framework will call this method exactly once for each State object it creates.

So, it means when your created widget is seen on the screen call once. But the build method call for a number of different situations.

The framework calls this method in a number of different situations. For example:

After calling initState. After calling didUpdateWidget. After receiving a call to setState. After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes). After calling deactivate and then reinserting the State object into the tree at another location.

If you want the further description you can visit flutter documentation.

Also in your case; _imageUrlFocusNode.addListener(_updateImageUrl); if you add this code inside build method. You will probably have many listeners so memory usage will increase.

  • Related