Explain it simply
Explain it simply
A class is the blueprint and a constructor is the assembly line that turns the blueprint into one finished object. Everything an object needs has to be on the line before it leaves: a car cannot be delivered with the engine still missing. Dart takes this seriously, which is why a constructor's main job is to give every field its value.
A class can also have several assembly lines. The ordinary one builds a Point from x and y; another builds the origin without asking for anything; a third reads two numbers out of a list. Each line has its own name, so code that uses them reads like a sentence: Point.origin().
Problem → Why → Solution
The problem: a final field cannot be assigned in the constructor body
You want an immutable Box: once created, its size can never change, so you declare the field final. Then you write the constructor the way you would in many other languages, taking a parameter and assigning it to the field inside the body. Dart rejects it with two errors, "The setter 'size' isn't defined for the type 'Box'." and "Final field 'size' is not initialized." The second one is the real message: by the time the body starts, Dart insists that every final field already has a value.
Dropping final makes the errors disappear, but then any later code can change the size, which is the exact bug you wanted to prevent. Dart needs a way to run initialization before the body, and that is what a constructor's initializing formals and initializer list are for.
class Box {
final int size;
Box(int size) {
this.size = size; // too late: final fields must be set before the body runs
}
}Creating an object has two phases
In Dart, creating an object happens in two phases: first the fields are initialized, then the constructor body runs on a fully built object. A final field can receive its value only in the first phase: with an initializing formal (Box(this.size)), in an initializer list (Box(int s) : size = s), or at its declaration. When the body runs the field is already sealed, so assigning there is too late.
Core concept: generative, named and initializer-list constructors
A generative constructor has the same name as its class and its job is to produce a fully initialized object. The shortcut Point(this.x, this.y); is called an initializing formal: for each this.x parameter Dart copies the argument into the field x before the body runs, so most constructors need no body at all. Parameters can be positional, optional positional in square brackets ([this.age = 0]) or named in curly braces ({required this.name, this.age = 18}); named parameters are the better choice once a constructor takes more than two or three arguments, because the call site documents itself.
Dart does not allow two constructors with the same name, so alternative ways of creating an object get their own names: Point.origin(), Point.fromList(...). A named constructor can also forward to another one with a redirecting initializer, Point.unit() : this(1, 1);, so the real work lives in one place.
The part after the colon is the initializer list. It runs before the body and is the place, besides the field's own declaration and initializing formals, where a final field may be set: x = pair[0].toDouble(). It can read the constructor's parameters but not this, and it is also where you call the superclass (super(name)) and where an assert(...) can check a precondition. Asserts are checked only when they are enabled, for example with dart run --enable-asserts or in a Flutter debug build; they are not a substitute for validating user input.
What happens when you call Child()
----------------------------------
Child() is called
1. Child's field initializers
2. Child's initializer list
3. Parent constructor (its initializers first, then its body)
4. Child's body (runs last, on a fully initialized object)The order matters once classes inherit from each other: the field initializers and initializer list of the class being created run first, then the superclass constructor runs completely (its initializers and its body), and only then does the body of the class you called run. The snippet below prints that order.
String log(String message) {
print(message);
return message;
}
class Parent {
final String a = log('Parent field initializer');
Parent() {
print('Parent body');
}
}
class Child extends Parent {
final String b = log('Child field initializer');
final String c;
Child() : c = log('Child initializer list') {
print('Child body');
}
}
void main() {
Child();
}- Arguments arrive at the constructor
- The initializer list sets the fields
- The superclass constructor runs
- The constructor body runs last
By the time the body runs, every final field must already have its value.
General pattern
class Name {
final int a;
final int b;
Name(this.a, this.b); // generative, initializing formals
Name.alt(int value) : a = value, b = 0; // named + initializer list
Name.copy(Name o) : this(o.a, o.b); // redirecting
const Name.fixed() : a = 1, b = 2; // const (all fields final)
factory Name.cached() => _shared; // factory: may return an existing one
static final _shared = Name(0, 0);
}Everything after the colon is the initializer list. A constructor that begins with this(...) is redirecting and has no body. A const constructor needs every field to be final, and a factory has no this and returns a value instead.
Example: five ways to create a Point
This Point class has five ways to be created: the ordinary constructor, two named constructors (origin and vertical), fromList with an assert and a type conversion in its initializer list, and a redirecting unit() that forwards to another constructor. Note that both fields are final double: in Point(2, 3) the numbers are int literals, but in a double context they become 2.0 and 3.0. Predict what Point.unit() prints before you run it.
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;
Point.fromList(List<num> pair)
: assert(pair.length == 2, 'need exactly two numbers'),
x = pair[0].toDouble(),
y = pair[1].toDouble();
Point.unit() : this(1, 1);
@override
String toString() => 'Point($x, $y)';
}
void main() {
print(Point(2, 3));
print(Point.origin());
print(Point.vertical(10));
print(Point.fromList([4, 5.5]));
print(Point.unit());
}Code breakdown
- Initializing formals
Point(this.x, this.y);this.x and this.y copy the arguments straight into the final fields, so no body is needed. In Point(2, 3) the literals 2 and 3 become 2.0 and 3.0 because the field type is double.
- Named + initializer list
Point.origin() : x = 0, y = 0;Point.origin() is called with no arguments. The initializer list after the colon sets x and y, and the name alone tells the reader what the object is for.
- Parameter feeds the list
Point.vertical(double yValue) : x = 0, y = yValue;The initializer list can read the constructor's parameter (yValue). It gives x the value 0 and takes y from the parameter, so Point.vertical(10) is (0.0, 10.0).
- assert + conversion
x = pair[0].toDouble(),fromList accepts a List<num> and converts with toDouble() to match the field type. The assert above it reports a wrong-sized list early (when asserts are enabled), and Point.fromList([4, 5.5]) is (4.0, 5.5).
- Redirecting
Point.unit() : this(1, 1);this(1, 1) hands all the work to the main constructor. A redirecting constructor cannot have a body, so Point.unit() is the same as Point(1, 1), which is (1.0, 1.0).
Point(2.0, 3.0)
Point(0.0, 0.0)
Point(0.0, 10.0)
Point(4.0, 5.5)
Point(1.0, 1.0)Named parameters, required and super parameters
Named parameters such as {required this.name, this.age = 18, this.email} are passed by name: User(name: 'Aye', email: 'a@x.com'). Leaving out a required one is a compile error, one with a default (this.age = 18) may be omitted, and a nullable one without a default (this.email) becomes null when omitted. You can use optional positional parameters such as [this.age = 0] too, but with more arguments named ones read better. In a subclass, a super parameter such as Dog(super.name, this.breed) forwards the argument straight to the parent constructor, so you do not redeclare Animal's name. A redirect such as User.guest() : this(name: 'guest'); can pass named arguments as well.
class User {
final String name;
final int age;
final String? email;
User({required this.name, this.age = 18, this.email});
User.guest() : this(name: 'guest');
User.positional(this.name, [this.age = 0]) : email = null;
}
class Animal {
final String name;
Animal(this.name);
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
}
void main() {
final u = User(name: 'Aye', email: 'a@x.com');
print('${u.name} ${u.age} ${u.email}');
final g = User.guest();
print('${g.name} ${g.age} ${g.email}');
final p = User.positional('Su');
print('${p.name} ${p.age} ${p.email}');
final d = Dog('Rex', 'lab');
print('${d.name} ${d.breed}');
}const constructors and canonical instances
A const constructor creates immutable objects that can be built at compile time. The requirements are that all fields of the class are final and that the call site writes const (const Color(1, 2, 3)). Two const expressions with the same values share one object in memory (a canonical instance), whereas a call without const creates a new object every time. If an argument is not a compile-time constant, const is impossible: var n = 5; const Color(n, 0, 0) is "Not a constant expression." The effect is like a built-in cache, and Flutter can reuse a single instance of a const widget across rebuilds.
class Color {
final int r, g, b;
const Color(this.r, this.g, this.b);
}
void main() {
const c1 = Color(1, 2, 3);
const c2 = Color(1, 2, 3);
final c3 = Color(1, 2, 3);
final c4 = Color(1, 2, 3);
print(identical(c1, c2)); // true: one shared constant
print(identical(c3, c4)); // false: two separate objects
print(identical(c1, c3)); // false
}Factory constructors: caching and returning subtypes
A factory constructor does not have to create a new object the way a generative one does: with a return statement it can hand back an existing instance (a cache) or an instance of a subtype. That is why calling Logger('db') twice gives the same object, and why Shape.fromJson returns a Square or a Rect depending on the json. The limits are that a factory has no this and cannot use an initializer list; the fields are initialized by whichever constructor creates the object it returns. It is common to pair a factory with a private named constructor such as _internal so outsiders cannot call it directly.
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) {
print('creating logger $name');
}
void log(String message) => print('[$name] $message');
}
abstract class Shape {
double get area;
factory Shape.fromJson(Map<String, Object> json) {
return switch (json['type']) {
'square' => Square(json['side'] as double),
'rect' => Rect(json['w'] as double, json['h'] as double),
_ => throw FormatException('unknown shape: ${json['type']}'),
};
}
}
class Square implements Shape {
final double side;
Square(this.side);
@override
double get area => side * side;
}
class Rect implements Shape {
final double w, h;
Rect(this.w, this.h);
@override
double get area => w * h;
}
void main() {
final a = Logger('db');
final b = Logger('db');
final c = Logger('web');
print(identical(a, b));
print(identical(a, c));
a.log('hello');
print(Shape.fromJson({'type': 'square', 'side': 3.0}).area);
print(Shape.fromJson({'type': 'rect', 'w': 2.0, 'h': 5.5}).area);
try {
Shape.fromJson({'type': 'blob'});
} on FormatException catch (e) {
print(e.message);
}
}| Kind | Looks like | Use it when |
|---|---|---|
| Generative | Point(this.x, this.y); | The normal way to create and initialize an object |
| Named | Point.origin() | Alternative creation paths that deserve a descriptive name |
| Redirecting | Point.unit() : this(1, 1); | Forwarding all the work to another constructor |
| const | const Color(1, 2, 3) | Immutable compile-time constant objects |
| factory | factory Logger(name) | Returning a cached instance or a subtype |
In real projects
Where this shows up in real projects
JSON models are the classic case: User.fromJson(Map<String, Object?> json) is a named constructor (or factory) that turns a decoded map into an object. Flutter widgets are written almost entirely with constructors like const Greeting({super.key, required this.name}): const lets Flutter reuse a single instance and required stops you from forgetting the name. The core library uses the same ideas: DateTime.now(), Duration(minutes: 2), List.filled(3, 0) and List.generate are named or factory constructors.
Factory constructors power caches and singletons such as a shared Logger or database connection, and const constructors let you declare immutable configuration once and reuse it everywhere. When you design your own classes, ask whether the object can be valid when half built; if it cannot, make the constructor the only way in.
Common mistakes
Common mistakes
1. Assigning a final field inside the constructor body
Box(int size) { this.size = size; } fails with "Final field 'size' is not initialized." because the field needs its value before the body starts. Use an initializing formal, Box(this.size);, or an initializer list, Box(int s) : size = s;.
2. Using this inside an initializer list
Rect(this.w, this.h) : area = this.w * this.h; fails with "Can't access 'this' in a field initializer." because the object is not built yet. Use the parameter names instead: area = w * h; where w and h are the constructor parameters, not the fields.
3. Forgetting const, or passing a non-constant argument
Merely having a const constructor does not share instances: the call site must say const too. identical(Color(1, 2, 3), Color(1, 2, 3)) is false, while two identical const expressions give true. An argument that is not a constant, as in var n = 5; const Score(n), fails with "Not a constant expression." Drop the const or make the argument constant.
Best practices
Best practices
- Prefer initializing formals and keep the constructor body empty whenever you can.
- Use a named constructor instead of a flag parameter for alternative ways to create an object: Point.origin() is clearer than Point(0, 0, isOrigin: true).
- Give a class a const constructor when all of its fields are final, so equal values can share one instance.
- Use assert in the initializer list for programmer mistakes, and throw an exception for invalid input that comes from users, because asserts are not checked in release builds.
Mini challenge
Mini challenge: a Money class
Write a Money class that stores an amount in cents and offers four constructors: a main const one, a redirecting named one, a const named one and a factory that parses text.
- Set final int cents and final String currency through a const main constructor with initializing formals
- Money.dollars(int dollars) redirects to the main constructor with dollars * 100 cents and 'USD'
- const Money.zero() sets cents to 0 and currency to 'USD' in an initializer list
- factory Money.parse(String text) turns '7.25 EUR' into Money(725, 'EUR') and throws a FormatException when the text does not match
- toString prints '12.50 USD'; main() prints one object per constructor, identical(const Money.zero(), const Money.zero()), and the message from a failed parse
class Money {
// TODO: final cents (int) and currency (String)
// TODO: const main constructor with initializing formals
// TODO: Money.dollars(int dollars): redirect to the main constructor, USD
// TODO: const Money.zero(): set both fields in an initializer list
// TODO: factory Money.parse(String text): "7.25 EUR" -> Money(725, 'EUR'),
// throw a FormatException when the text does not match
// TODO: toString printing "12.50 USD"
}
void main() {
// TODO: print const Money(1250, 'USD'), Money.dollars(5), Money.zero(),
// identical(const Money.zero(), const Money.zero()),
// Money.parse('7.25 EUR'), and the message from a failed parse
}Expected: 12.50 USD 5.00 USD 0.00 USD true 7.25 EUR bad input: expected "12.50 USD" but got "lots"
Show hint
The redirecting constructor looks like Money.dollars(int dollars) : this(dollars * 100, 'USD'); with no body. Inside the factory split with text.split(' '), check double.tryParse(parts[0]), throw when it is null, and otherwise return Money((amount * 100).round(), parts[1]). In toString use cents ~/ 100 and cents % 100, and pad the cents to two digits with padLeft(2, '0').
Show solution
class Money {
final int cents;
final String currency;
const Money(this.cents, this.currency);
Money.dollars(int dollars) : this(dollars * 100, 'USD');
const Money.zero() : cents = 0, currency = 'USD';
factory Money.parse(String text) {
final parts = text.split(' ');
final amount = parts.length == 2 ? double.tryParse(parts[0]) : null;
if (amount == null) {
throw FormatException('expected "12.50 USD" but got "$text"');
}
return Money((amount * 100).round(), parts[1]);
}
@override
String toString() {
final units = (cents ~/ 100).toString();
final rest = (cents % 100).toString().padLeft(2, '0');
return '$units.$rest $currency';
}
}
void main() {
print(const Money(1250, 'USD'));
print(Money.dollars(5));
print(Money.zero());
print(identical(const Money.zero(), const Money.zero()));
print(Money.parse('7.25 EUR'));
try {
Money.parse('lots');
} on FormatException catch (e) {
print('bad input: ${e.message}');
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Initializing formals (this.x) copy arguments into fields before the body, so most constructors need no body; final fields can be set only this way or in the initializer list.
- Named constructors give alternative creation paths a name, and a redirecting constructor forwards to the main one with this(...).
- The run order is Child's field initializers and initializer list, then the whole Parent constructor, and finally Child's body.
- A const constructor creates immutable canonical objects, and a factory can return a cached or subtype instance but has no this.
Dart language overview — Dart