Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't initialize final property inside Dart constructor

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading