TExcelTAD
Home › Dart › Dart Constructors

Dart Constructors

A constructor creates and initialises an instance. Dart has an unusually rich set of constructor forms: generative, named, redirecting, const and factory constructors, plus initializer lists and super parameters. Knowing them lets you write classes that are concise and safe.

Generative constructors and initializing formals

dart · try it yourself
class Rectangle {
  final double width;
  final double height;

  Rectangle(this.width, this.height);           // unnamed constructor
  Rectangle.square(double side) : this(side, side); // named, redirects
  Rectangle.fromMap(Map<String, double> m)       // named
      : width = m['w'] ?? 0,
        height = m['h'] ?? 0;

  double get area => width * height;
}

void main() {
  print(Rectangle(2, 5).area);
  print(Rectangle.square(3).area);
  print(Rectangle.fromMap({'w': 4, 'h': 1.5}).area);
}
10.0
9.0
6.0
Form Syntax Use
Unnamed Rectangle(this.w, this.h); The main way to build an object
Named Rectangle.square(double s) Alternative ways — Dart has no overloading, so named constructors fill that role
Redirecting : this(s, s); Delegate to another constructor

Initializer lists

Code after the : and before the body runs before the object exists. Use it to compute final fields, validate arguments with assert, or call super:

dart · try it yourself
class Temperature {
  final double celsius;
  final double fahrenheit;

  Temperature(this.celsius)
      : assert(celsius >= -273.15, 'below absolute zero'),
        fahrenheit = celsius * 9 / 5 + 32;

  Temperature.fromFahrenheit(double f)
      : fahrenheit = f,
        celsius = (f - 32) * 5 / 9;

  @override
  String toString() =>
      '${celsius.toStringAsFixed(1)}°C = ${fahrenheit.toStringAsFixed(1)}°F';
}

void main() {
  print(Temperature(25));
  print(Temperature.fromFahrenheit(212));
}
25.0°C = 77.0°F
100.0°C = 212.0°F

Note: The initializer list can't use this (the object isn't built yet). That's why fahrenheit is computed from the parameter celsius, not from the field.

Named and required parameters in constructors

dart · try it yourself
class Email {
  final String to;
  final String subject;
  final List<String> cc;
  final bool urgent;

  const Email({
    required this.to,
    this.subject = '(no subject)',
    this.cc = const [],
    this.urgent = false,
  });

  @override
  String toString() => '${urgent ? '[!] ' : ''}$subject -> $to${cc.isEmpty ? '' : ' cc $cc'}';
}

void main() {
  print(Email(to: 'an@shop.vn'));
  print(Email(to: 'bo@shop.vn', subject: 'Invoice', cc: ['acct@shop.vn'], urgent: true));
}
(no subject) -> an@shop.vn
[!] Invoice -> bo@shop.vn cc [acct@shop.vn]

const constructors

If all fields are final, a constructor can be const. Calling it with const creates a compile-time constant, and identical constants are shared — one instance no matter how often you write it:

dart · try it yourself
class Color {
  final int r, g, b;
  const Color(this.r, this.g, this.b);
  static const black = Color(0, 0, 0);
}

void main() {
  const a = Color(10, 20, 30);
  const b = Color(10, 20, 30);
  final c = Color(10, 20, 30); // not const: a new object

  print(identical(a, b));
  print(identical(a, c));
  print(identical(Color.black, const Color(0, 0, 0)));
}
true
false
true

This is why Flutter encourages const widgets: the framework can skip rebuilding constants.

Factory constructors

A factory constructor doesn't have to create a new instance. It can return a cached one, an instance of a subtype, or do work before construction. It's written like a normal function body with a return:

dart · try it yourself
class Logger {
  static final _cache = <String, Logger>{};
  final String name;

  Logger._internal(this.name) {
    print('creating logger $name');
  }

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

  factory Logger.fromJson(Map<String, Object?> json) => Logger(json['name'] as String);

  void log(String msg) => print('[$name] $msg');
}

void main() {
  final a = Logger('db');
  final b = Logger('db');
  final c = Logger.fromJson({'name': 'ui'});
  a.log('connected');
  c.log('rendered');
  print(identical(a, b));
}
creating logger db
creating logger ui
[db] connected
[ui] rendered
true

Logger._internal is a private named constructor: code in other files can only use the factory. fromJson factories are the standard way to build model objects from decoded JSON.

Super parameters

When a subclass passes arguments straight through to its superclass, Dart 2.17+ lets you write super.name instead of repeating them:

dart
class Animal {
  final String name;
  final int legs;
  Animal(this.name, {this.legs = 4});
}

// Before: Dog(String name, {int legs = 4}) : super(name, legs: legs);
class Dog extends Animal {
  final bool goodBoy;
  Dog(super.name, {super.legs, this.goodBoy = true});
}

super.name forwards the positional argument, super.legs forwards the named one — and the superclass default (4) still applies. You'll see this in Inheritance.

Construction order

  1. Initializing formals (this.x, super.x) and the initializer list run, top to bottom.
  2. The superclass constructor runs (implicitly super() if not written).
  3. The constructor body runs — now this is available.

Test yourself

Why does Dart use named constructors like Rectangle.square()?

  1. For speed
  2. Because Dart has no constructor overloading
  3. They are required for const
  4. To make fields private

What can a factory constructor do that a generative constructor can't?

  1. Take named parameters
  2. Return an existing (cached) instance or a subtype
  3. Initialize final fields
  4. Be called without new

When does the initializer list run?

  1. After the constructor body
  2. Before the constructor body, before this is available
  3. Only for const constructors
  4. Lazily, on first field access