Flutter: Difference in initializing variables in a Class

4,851

Solution 1

The difference is that the first variable cannot be assigned dynamic content to, like AnimationController(vsync: this), you have to do that in initState.

I would guess initState assigning decreases performance a little bit, because you have more options.

I'd recommend using the regular assigning of variables whenever it's possible, and using initState() only when you have to.

Solution 2

In your first example, the assignment takes place during construction. You might want to use this form if name is final.

In the second example, the assignment takes place when initState is called, which could be zero, one or more times. Presumably you are referring to the initState of State<T> which the framework calls once, after construction.

Share:
4,851
ZeroNine
Author by

ZeroNine

Updated on December 07, 2022

Comments

  • ZeroNine
    ZeroNine over 1 year

    Currently I'm assigning all variables through initState however I'm seeing that there is no need to assign the variables through initState as I can just assign the variable with a value directly. What is the order of these assignments and how are they different? Why and when would you choose one instead of the other?

    class Person {
      String name = "John";
    
      @override
      void initState(){
      ....
      ....
      }
    }
    

    vs

    class Person {
      String name;
      @override
      void initState(){
        name = "John";
      }
    }