Thuta Learning
IntermediateProgrammingbeginner

Constructors

Relax. We'll talk through this in plain words — no textbook voice.

Constructor is the special method that runs when a class creates a new object. Dart gives you several ways to write one — short-form constructors, named constructors, initializer lists, and more.

dart
class Point {
  final double x;
  final double y;

  Point(this.x, this.y);

  Point.origin()
      : x = 0,
        y = 0;

  Point.vertical(double yValue)
      : x = 0,
        y = yValue;
}

void main() {
  final p1 = Point(2, 3);
  final p2 = Point.origin();
  final p3 = Point.vertical(10);

  print('p1: ${p1.x}, ${p1.y}');
  print('p2: ${p2.x}, ${p2.y}');
  print('p3: ${p3.x}, ${p3.y}');
}

Point(this.x, this.y) is a normal constructor. Point.origin() and Point.vertical() are named constructors, and their names describe the purpose of the object they create.

You should see
p1: 2.0, 3.0 p2: 0.0, 0.0 p3: 0.0, 10.0

Easy traps

  • When using a named constructor, call it with a dot after the class name followed by the constructor name — for example, Point.origin().
Constructors | Thuta Learning