Reputation: 163
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.
Upvotes: 11
Views: 6099
Reputation: 90095
In your trivial case, it doesn't matter.
In general, you can initialize instance variables in a few ways:
class Example1 {
T x = value;
}
Advantages:
final
or non-nullable members.Disadvantages:
this
since the initialization occurs before this
becomes valid (i.e., cannot depend on other instance members). (An exception is if the member is initialized lazily by declaring it late
. This requires the null-safety feature to be enabled.)class Example2 {
T x;
Example2() : x = value;
}
Advantages:
final
or non-nullable members.Disadvantages:
this
since the initialization occurs before this
becomes valid (i.e., cannot depend on other instance members).class Example3 {
T x;
Example3() {
x = value;
}
}
Advantages:
this
(i.e., can use other instance members).Disadvantages:
late
final
nor 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 this
becomes valid only for the later stages of object initialization.
As an example where it matters where members are initialized:
class Base {
Base() {
doSomething();
}
void doSomething() {}
}
class DerivedEarly extends Base {
int? x;
DerivedEarly() : x = 42;
@override
void doSomething() => print(x);
}
class DerivedLate extends Base {
int? x;
DerivedLate() {
x = 42;
}
@override
void doSomething() => print(x);
}
void main() {
DerivedEarly(); // Prints: 42
DerivedLate(); // Prints: null
}
Upvotes: 32