In Java you are allowed to do this:
class A {
private final int x;
public A() {
x = 5;
}
}
In Dart, I tried:
class A {
final int x;
A() {
this.x = 5;
}
}
I get two compilation errors:
The final variable 'x' must be initialized.
and
'x' can't be used as a setter because its final.
Is there a way to set final properties in the constructor in Dart?
You can make it even shorter with
this.
syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):If you have some more complicated initialization you should use factory constructor, and the code become:
You cannot instantiate final fields in the constructor body. There is a special syntax for that:
I've come to a dilemma here where I wanted to initialize a final List with no items, and a
Stream
to be defined inside the constructor (like in this casedistanceFromOrigin
).I couldn't do that with any of the answers below, but I mixed them both and it worked.
Example: