How do I initialize a final class property in a constructor? How do I initialize a final class property in a constructor? dart dart

How do I initialize a final class property in a constructor?


You cannot instantiate final fields in the constructor body. There is a special syntax for that:

class Point {  final num x;  final num y;  final num distanceFromOrigin;  // Old syntax  // Point(x, y) :  //   x = x,  //   y = y,  //   distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));  // New syntax  Point(this.x, this.y) :    distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));}


You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):

class Point {  final num x;  final num y;  final num distanceFromOrigin;  Point(this.x, this.y)      : distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));}

If you have some more complicated initialization you should use factory constructor, and the code become:

class Point {  final num x;  final num y;  final num distanceFromOrigin;  Point._(this.x, this.y, this.distanceFromOrigin);  factory Point(num x, num y) {    num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));    return new Point._(x, y, distance);  }}


I've had a similar problem: I was trying to initialise a final field from the constructor, while simultaneously calling a super constructor. You could think of the following example

class Point2d {  final int x;  final int y;  Point2d.fromCoordinates(Coordinates coordinates)      : this.x = coordinates.x,        this.y = coordinates.y;}class Point3d extends Point2d {  final int z;  Point3d.fromCoordinates(Coordinates coordinates)      :this.z = coordinates.z,        super.fromCoordinates(coordinates);}
/// Demo class, to simulate constructing an object/// from another object.class Coordinates {  final int x;  final int y;  final int z;}

Well apparently this works. You can initialise your final fields by using the above syntax (check Point3d's constructor) and it works just fine!

Run a small program like this to check:

void main() {  var coordinates = Coordinates(1, 2, 3);  var point3d = Point3d.fromCoordinates(coordinates);  print("x: ${point3d.x}, y: ${point3d.y}, z: ${point3d.z}");}

It should prin x: 1, y: 2, z: 3