A generative constructor with this.x assigns positional arguments to final fields. Named constructors give a class extra ways to build itself, with an initializer list : x = ..., y = ... setting the fields before the body runs.

Program

Play the program to build a Point three different ways.

constructors.dart
Replay: real traced execution (multi-file project)
class Point {
  final int x;
  final int y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  Point.diagonal(int n) : x = n, y = n;
}

void main() {
  var a = Point(3, 4);
  var b = Point.origin();
  var c = Point.diagonal(5);
  print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');
}
  1. a ← Point(x: 3, y: 4)

    9void main() {10  var a = Point(3, 4);11  var b = Point.origin();
    values this stepPoint(x: 3, y: 4)a
  2. call ← Point.origin()

    10var a = Point(3, 4);11var b = Point.origin();12var c = Point.diagonal(5);
    values this stepPoint.origin()call
  3. init list ← x = 0, y = 0

    4Point(this.x, this.y);5Point.origin() : x = 0, y = 0;6Point.diagonal(int n) : x = n, y = n;
    values this stepx = 0, y = 0init list
  4. b ← Point(x: 0, y: 0)

    10var a = Point(3, 4);11var b = Point.origin();12var c = Point.diagonal(5);
    values this stepPoint(x: 0, y: 0)b
  5. call ← Point.diagonal(5)

    11var b = Point.origin();12var c = Point.diagonal(5);13print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');
    values this stepPoint.diagonal(5)call
  6. init list ← x = 5, y = 5

    5  Point.origin() : x = 0, y = 0;6  Point.diagonal(int n) : x = n, y = n;7}
    values this stepx = 5, y = 5init list5n
  7. c ← Point(x: 5, y: 5)

    11var b = Point.origin();12var c = Point.diagonal(5);13print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');
    values this stepPoint(x: 5, y: 5)c
  8. print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');

    12  var c = Point.diagonal(5);13  print('${a.x},${a.y} ${b.x},${b.y} ${c.x},${c.y}');14}
    output3,4 0,0 5,5
    values this stepPoint(3, 4)aPoint(0, 0)bPoint(5, 5)c
generative `Point(this.x, this.y)` assigns straight to `final` fields from positional arguments.
named constructor `Point.origin()` and `Point.diagonal(n)` are extra named ways to build a `Point`.
initializer list `: x = 0, y = 0` runs before the body and is required when `final` fields need values.