Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 61 ยท Classes and Object-Oriented Dart

Constructors

Learn every kind of Dart constructor: generative, named, initializing formals, initializer lists, redirecting, factory and const constructors, with examples.

A constructor is the code that builds an object. In many languages there is one constructor per class and you work around that limit with overloads. Dart has no overloading, so it gives you something better: a small family of constructor forms, each with a clear job. You can name constructors, set final fields before the body runs, forward one constructor to another, return a cached object from a factory, and even build objects at compile time.

This lesson walks through all of them using one running example. Dart code is read-only; the stand-ins use TypeScript classes, static methods and private constructors, which model the same ideas. If you have not met classes yet, start with Classes and Objects.

Generative constructors and initializing formals

A constructor with the same name as the class creates a new instance. That kind is called generative. The long way to write one assigns each parameter to a field:

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

  Point(double x, double y)
      : x = x,
        y = y;
}

Because this pattern is so common, Dart offers initializing formals: write this.x in the parameter list and the argument goes straight into the field.

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

  Point(this.x, this.y);

  @override
  String toString() => 'Point($x, $y)';
}

void main() {
  var p = Point(3, 4);
  print(p);   // Point(3.0, 4.0)
}

Notice the missing new: you create an object by calling the class like a function. The constructor above has no body, just a semicolon. Initializing formals also work with named and optional parameters, and a type is not needed because it comes from the field. Since a final field can only be set once, it must be set by the time the constructor body starts running. That rule explains the next feature.

Initializer lists

Between the parameter list and the body you can place a colon and a comma-separated initializer list. It runs before the body, and it is the place to set final fields from computed values, to check assumptions with assert, and to call a superclass constructor.

DART
class Circle {
  final double radius;
  final double area;

  Circle(this.radius)
      : assert(radius >= 0, 'radius must not be negative'),
        area = 3.14159 * radius * radius;
}

Inside the initializer list you cannot use this, because the object is not fully built yet, but you can use the parameters. The assert runs only in debug mode (see Assertions and Debugging). The order of work is always the same: initializer list first, then the superclass constructor, then the constructor body.

flowchart LR
    A["Call Circle(5)"] --> B["Initializing formals<br/>and initializer list"]
    B --> C["Superclass<br/>constructor"]
    C --> D["Constructor body"]
    D --> E["Finished object"]

Fields are set first, the parent is built next, and the body runs last.

Named constructors

Dart lets a class have as many constructors as it wants, as long as each has a different name. A named constructor is written ClassName.name.

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

  const Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  Point.fromList(List<double> pair) : x = pair[0], y = pair[1];
  Point.polar(double radius, double angle)
      : x = radius * math.cos(angle),
        y = radius * math.sin(angle);
}

Names tell the reader what the constructor means: Point.origin() reads better than Point(0, 0), and Point.polar(2, 1.57) cannot be mixed up with the plain form. Standard classes use this a lot: List.filled(3, 0), DateTime.now(), Duration(seconds: 5). Named constructors are not inherited, so a subclass must declare its own if it wants them.

TypeScript Named constructors (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Redirecting constructors

Sometimes one constructor is just a shortcut for another. A redirecting constructor has no body and no initializers; it forwards to a different constructor of the same class with this.

DART
class Rectangle {
  final double width;
  final double height;

  Rectangle(this.width, this.height);
  Rectangle.square(double side) : this(side, side);
  Rectangle.unit() : this.square(1);
}

The work stays in one place, the main constructor, so validation or logic you add there applies to every shortcut. This is the same idea as constructor chaining in other languages, expressed as a short declaration.

Constant constructors

If every field of a class is final and the constructor does all its work in the initializer list, mark the constructor const. You can then create compile-time constants:

DART
class Color {
  final int red, green, blue;
  const Color(this.red, this.green, this.blue);
}

void main() {
  var a = const Color(255, 0, 0);
  var b = const Color(255, 0, 0);
  print(identical(a, b));   // true: one shared object
}

Two const expressions with equal arguments produce the same object, which saves memory and makes comparisons cheap. Flutter relies on this heavily for widgets. Without the keyword at the call site (Color(255, 0, 0)), you get an ordinary object even though the constructor is const. Inside a const context, such as a const list, the keyword is optional.

Factory constructors

A factory constructor is different: it does not have to create a new instance. It is a function that must return an object of the class (or a subtype). That makes it perfect for caching, choosing between subclasses and returning an existing instance.

DART
class Logger {
  static final Map<String, Logger> _cache = {};

  final String name;

  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }

  Logger._internal(this.name);
}

void main() {
  var a = Logger('db');
  var b = Logger('db');
  print(identical(a, b));   // true
}

Two points to notice. First, the private named constructor Logger._internal (any name starting with an underscore is private to its library) is how a class stops outsiders from building instances by hand. Second, a factory has no this, so it cannot use initializer lists or initializing formals; it calls another constructor to do the real construction. A factory can also parse data, like factory User.fromJson(Map<String, dynamic> json), a pattern you will use in JSON and Serialization.

TypeScript A caching factory and a private constructor (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Choosing the right constructor

A short decision guide:

  • Plain data, fields known up front: generative constructor with initializing formals.
  • Computed final fields or validation: add an initializer list.
  • A common special case or alternative input: named constructor.
  • Many shortcuts to one real constructor: redirecting.
  • Immutable value objects used often: const.
  • Caching, choosing a subtype or parsing input before building: factory.

If a field is late or nullable you can also assign it inside the constructor body, but prefer final fields set by the initializer list: they make objects immutable and always fully built.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Point(this.x, this.y); do?

    this.x in the parameter list is an initializing formal. The argument is stored in the field of the same name before the body runs.
  2. 2. Where can you set a final field from a computed value, before the constructor body runs?

    The initializer list runs before the body, which is the only time a final field can be assigned in a constructor.
  3. 3. Why are two const Color(255, 0, 0) expressions identical?

    Constant expressions with equal arguments are canonicalized, so both refer to a single shared instance.
  4. 4. Which statement about a factory constructor is true?

    A factory is a function that returns an instance. It can return a cached object or an instance of a subclass, but it has no this and no initializer list.
  5. 5. What is a redirecting constructor?

    Rectangle.square(double side) : this(side, side); hands all the work to the main constructor of the same class.

Summary

  • Use this.field in the parameter list (initializing formals) to avoid boilerplate.
  • The initializer list runs before the body and the right place for final fields, assert and super calls.
  • Named constructors give different ways to build an object clear names; they are not inherited.
  • Redirecting constructors forward to another constructor with : this(...).
  • const constructors create canonical compile-time constants when all fields are final.
  • factory constructors return existing or subtype instances; a private _internal constructor stops outside construction.

Next, control how fields are read and written in Getters, Setters and Properties.