I would like to create a class in Dart with a final List
property that it's just empty in the beginning and can be populated later. With the code bellow I am getting the error "numbers can't be used as a setter because it's final". What confuses me here is that the variable is initialized inside the constructor.
class Foo {
final String s;
final List<int> numbers;
Foo(this.s) {
numbers = List<int>(); // error
}
}
What's the best way to do this?
CodePudding user response:
Initialize instance variables in the initializer list of the constructor:
Foo(this.s) : numbers = <int>[];
In Dart, final variables are unassignable the moment the constructor body starts running.
The code inside the constructor body is just normal code which can access the object, and do anything with it.
Dart ensures that nobody can ever see a final instance variable in an uninitialized state by requiring final variables to be initialized before the constructor body starts, which means in the initializer list (or as an initializing formal like this.s
, or by having an initializer expression on the variable declaration itself.)
(The List()
constructor is heavily deprecated and going away real soon now, so use list literals to create lists instead.)