Skip to content
Justice Tech School

Constructors

Named constructors, factory constructors and initialiser lists give flexibility.

Example
class Point {
  final int x, y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  factory Point.fromList(List<int> l) => Point(l[0], l[1]);
}
void main() {
  print(Point.origin().x);
  print(Point.fromList([3, 4]).y);
}

Exercise

Named constructor.

Point.() : x = 0

Quiz Test

What does factory allow?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.