Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Difference in initializing variables in a Class

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";
  }
}
like image 210
ZeroNine Avatar asked Nov 20 '18 00:11

ZeroNine


1 Answers

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.

like image 147
Richard Heap Avatar answered Oct 10 '22 23:10

Richard Heap