๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Constructors in Depth

A class can offer more than one constructor. Named constructors give each extra way of building an object its own name.

A redirecting constructor

Point.right builds a point on the x axis. It forwards to the unnamed constructor with y set to 0.

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);

  Point.right(int n) : this(n, 0);

  @override
  String toString() {
    return '($x, $y)';
  }
}

void main() {
  print(Point.right(5));
}

A const constructor

Both points are const with equal fields. identical reports true because they are one object.

class Point {
  final int x;
  final int y;

  const Point(this.x, this.y);

  @override
  String toString() {
    return '($x, $y)';
  }
}

void main() {
  print(identical(const Point(1, 2), const Point(1, 2)));
  print(const Point(1, 2));
}

Named and unnamed together

One class offers three ways to build a point. Each call picks the constructor by name.

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);

  Point.origin() : this(0, 0);

  Point.right(int n) : this(n, 0);

  @override
  String toString() {
    return '($x, $y)';
  }
}

void main() {
  print(Point.origin());
  print(Point(3, 4));
  print(Point.right(7));
}

Example

class Point {
  final int x;
  final int y;

  const Point(this.x, this.y);

  Point.square(int n) : this(n, n);

  Point.right(int n) : this(n, 0);

  @override
  String toString() {
    return '($x, $y)';
  }
}

void main() {
  print(Point.square(2));
  print(Point.right(9));
  print(identical(Point(1, 1), Point(1, 1)));
  print(identical(const Point(1, 1), const Point(1, 1)));
}

Key points

  • A named constructor reads ClassName.name and sits beside the unnamed constructor.
  • A redirecting constructor forwards its arguments to another constructor of the same class with this(...).
  • A redirecting constructor has no body of its own.
  • A const constructor needs final fields, and equal const objects become one shared object.
  • identical proves the sharing, since two equal const points are the same object.

In this example, square redirects with both coordinates equal and right redirects with y as 0. Two plain points with equal fields are still separate objects. Two const points with equal fields are the same object.

Note

a class can mix the unnamed constructor, named constructors, and a const form in one file.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does identical(const Point(1, 2), const Point(1, 2)) print?