Hydrocat Hydrocat - 3 months ago 8
Dart Question

What does the ":" means in class constructors in dart?

I was reading dartlang.org resource on classes and they note the following construction:

import 'dart:math';

class Point {
final num x;
final num y;
final num distanceFromOrigin;

Point(x, y)
: x = x,
y = y,
distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}


What I don't quite understand is the ":" in the Point Constructor and why/when should I use it?

Answer

It starts the "initializer list".

If you have final fields like the ones in your Point class, then there are different ways to initialize them.

class Point {
  final num x = 3;
  ...
}

class Point {
  final num x;
  constructor(this.x);
}

class Point {
  final num x;
  constructor(num x) : this.x = x * 3;
}

This wouldn't work

class Point {
  final num x = 3;
  constructor(num x) {
    this.x = x * 3;
  }
}

because final fields can't be modified from within the constructor.

The initializer list a way to work around this limitation while still conforming to guarantees about object initialization order. It is executed before the constructor body. It is a way to check or modify (assign default values) passed parameters before they are assigned to final fields and also do some calculations.

Using this in the initializer list is only allowed to assign to properties, but not to read from them to prevent access to not-yet-initialized properties.

The call to the super constructor also is done in the initializer list and should usually be the last call in the list.

class MyPoint extends Point {
  constructor(num x) : super(x);
}