How to set final/const properties in Dart constructor How to set final/const properties in Dart constructor dart dart

How to set final/const properties in Dart constructor


From the Dart language tour:

Note: Instance variables can be final but not const. Final instance variables must be initialized before the constructor body starts — at the variable declaration, by a constructor parameter, or in the constructor’s initializer list.

And the section on initializer lists says:

Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.

// Initializer list sets instance variables before// the constructor body runs.Point.fromJson(Map<String, num> json)    : x = json['x'],      y = json['y'] {  print('In Point.fromJson(): ($x, $y)');}

So the general way is through initialization lists.

As mentioned above, you also can initialize at variable declaration:

class Foo {  final x = 42;}

or can initialize them by a constructor parameter:

class Foo {  final x;  Foo(this.x);}

although those other approaches might not always be applicable.