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
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:
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 whyfahrenheitis computed from the parametercelsius, not from the field.
Named and required parameters in constructors
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:
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:
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:
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
- Initializing formals (
this.x,super.x) and the initializer list run, top to bottom. - The superclass constructor runs (implicitly
super()if not written). - The constructor body runs — now
thisis available.
Test yourself
Why does Dart use named constructors like Rectangle.square()?
- For speed
- Because Dart has no constructor overloading
- They are required for const
- To make fields private
What can a factory constructor do that a generative constructor can't?
- Take named parameters
- Return an existing (cached) instance or a subtype
- Initialize final fields
- Be called without
new
When does the initializer list run?
- After the constructor body
- Before the constructor body, before
thisis available - Only for const constructors
- Lazily, on first field access