In Dart, is there a difference in assigning values right away vs in constructor like in Java?
class Example {
int x = 3;
}
vs
class Example {
int x;
Example() {
x = 3;
}
}
I ask because when I was using Flutter and tried to assign a Function that uses setState to a variable, it was not possible with the former method but possible with the latter.
In your trivial case, it doesn't matter.
In general, you can initialize instance variables in a few ways:
Inline (field initializers)
Advantages:
finalor non-nullable members.Disadvantages:
thissince the initialization occurs beforethisbecomes valid (i.e., cannot depend on other instance members). (An exception is if the member is initialized lazily by declaring itlate. This requires the null-safety feature to be enabled.)Initializer list
Advantages:
finalor non-nullable members.Disadvantages:
thissince the initialization occurs beforethisbecomes valid (i.e., cannot depend on other instance members).Constructor body
Advantages:
this(i.e., can use other instance members).Disadvantages:
latefinalnor non-nullable members.There probably are some points I'm forgetting, but I think that should cover the main ones.
Direct, inline initialization occurs first, then initialization lists, then constructor bodies. Also see Difference between assigning the values in parameter list and initialiser list, which explains why
thisbecomes valid only for the later stages of object initialization.As an example where it matters where members are initialized: