Sub topic 5
Generative constructors and initializing formals
This chapter assumes you know basic Dart syntax, null safety (nullable and non-nullable types), and the difference between a class and an object. It covers the most common kind of constructor in Dart and the shorthand that removes most of the boilerplate around it.
What a generative constructor is
A generative constructor is a constructor that creates a new instance of its own class. It is the default kind. When you write Point(1, 2), Dart allocates a new object, runs the constructor, and gives you the object. The constructor never returns a value, and it cannot return an existing object. Returning a cached or different instance requires a factory constructor, which a later chapter covers.
A generative constructor has the same name as its class:
class Counter {
int value;
Counter(int start) : value = start;
}Here Counter(int start) is the constructor. The part after the colon is an initializer list, which sets value before the constructor body would run. A later chapter covers initializer lists in depth. This chapter focuses on a shorter way to write the same thing.
The implicit default constructor
If you declare no constructor, Dart gives the class an implicit constructor with no parameters and no body. It calls the superclass's unnamed, zero-argument constructor.
class Empty {}
void main() {
final e = Empty();
print(e.runtimeType);
}The implicit constructor disappears as soon as you declare any constructor, including a named one. After that, Empty() is a compile error unless you write the unnamed constructor yourself.
Initializing formals
Most constructors do one thing: copy each parameter into a field with the same name. Without shorthand, that takes repetition:
class VerbosePoint {
final double x;
final double y;
VerbosePoint(double x, double y)
: x = x,
y = y;
}An initializing formal replaces each parameter and its assignment with this.fieldName in the parameter list:
class Point {
final double x;
final double y;
Point(this.x, this.y);
}
void main() {
const p = Point(3, 4);
print('${p.x}, ${p.y}');
}The constructor has no body, and the semicolon ends it. Point(this.x, this.y) means "declare a parameter named x and assign its value to the field x". The parameter takes its type from the field, so you do not repeat double.
A few details:
- The assignment happens during initialization, before the body runs. That is why initializing formals work with
finalfields. - You can write a type, as in
double this.x. It must be a subtype of the field's type, which makes it rarely useful. - The parameter is not in scope as a separate variable named
xinside an initializer list. Use the field name only when you mean the field.
The example above also shows that this chapter's Point has no const constructor, so const p = Point(3, 4) would fail. The next constructor chapters cover const. Write final p = Point(3, 4); to run it as shown.
Here is the corrected, runnable version:
class Point {
final double x;
final double y;
Point(this.x, this.y);
}
void main() {
final p = Point(3, 4);
print('${p.x}, ${p.y}');
}Why a body assignment is not enough
You might expect to write the assignments in the body:
class BrokenPoint {
final double x;
final double y;
BrokenPoint(double x, double y) {
this.x = x; // error
this.y = y; // error
}
}This does not compile. A final field can be assigned only once, and Dart requires non-nullable fields to hold a value before the constructor body starts, because the body can already call methods that read them. Initializing formals and initializer lists run before the body, which makes them safe places for the first assignment. The only way to assign a non-nullable, non-late field in a body is to give it an initial value some other way.
Positional, optional, and named parameters
Initializing formals work with every parameter style a function supports. Defaults follow the usual rules.
| Style | Example | Notes |
|---|---|---|
| Required positional | `Point(this.x, this.y)` | Callers must pass both, in order. |
| Optional positional | `Point([this.x = 0, this.y = 0])` | Needs a default unless the field is nullable. |
| Named, optional | `Point({this.x = 0, this.y = 0})` | Needs a default unless the field is nullable. |
| Named, required | `Point({required this.x, required this.y})` | Callers must pass every one, by name. |
A realistic example mixes them:
class User {
final String name;
final int age;
final String? email;
User(this.name, {this.age = 18, this.email});
}
void main() {
final u = User('Ada', email: '[email protected]');
print('${u.name} ${u.age} ${u.email}');
}name is required and positional. age falls back to 18. email is nullable, so it needs no default and is null if omitted.
A common error is declaring a non-nullable named parameter with no default and no required. Dart rejects it, because the field would have no value when the caller leaves it out. Add required, add a default, or make the field nullable.
Private fields and initializing formals
Fields whose names start with an underscore are private to their library. An initializing formal with a private name works for positional parameters:
class Account {
double _balance;
Account(this._balance);
double get balance => _balance;
}The parameter itself is not private in a harmful way here, because callers pass it by position and never write its name. A named parameter is different. In most Dart SDK versions, a named parameter cannot start with an underscore, since code in another library could not write Account(_balance: 5). Check your SDK version's release notes, because this rule has been under change. When you need a private field with a public named parameter, use an initializer list:
class Wallet {
double _balance;
Wallet({required double balance}) : _balance = balance;
}The order of initialization
Dart builds an object in a fixed order. Knowing it explains most constructor errors.
This program prints each step:
int _trace(String message) {
print(message);
return 1;
}
class Base {
Base() {
print('3. Base body');
}
}
class Child extends Base {
final int a = _trace('1. field initializer');
final int b;
final int c;
Child(this.b)
: c = _trace('2. initializer list'),
super() {
print('4. Child body, b = $b');
}
}
void main() {
Child(5);
}The output is:
1. field initializer
2. initializer list
3. Base body
4. Child body, b = 5Two consequences follow:
- The superclass constructor runs after your own field initialization but before your body. When your body runs, the inherited part of the object is complete.
- The
super()call must come last in the initializer list. If you omit it, Dart calls the superclass's unnamed zero-argument constructor for you. If that constructor does not exist, you get a compile error and must call a specific superclass constructor yourself.
Common errors
- "Final field must be initialized." You declared a
finalor non-nullable field and no constructor sets it. Add an initializing formal, an initializer, or an inline value. - "The implicit call to super() ... no default constructor." The superclass has only constructors that need arguments. Add an explicit
super(...)call to your initializer list. - Assigning in the body. Use initializing formals or the initializer list for
finalfields. - Using
this.in a parameter of a regular function. Initializing formals work in constructors only. They are not allowed in ordinary methods. - Redeclaring a field type in the parameter. Writing
Point(double this.x)is legal but noise. Preferthis.x.
Exercise
A class declares final String id; and final DateTime created;. You want created to default to the current time when the caller omits it, and you want id to be a required named parameter. Can you do this with initializing formals alone? Write the constructor.
Show answer
Only partly. id works with an initializing formal: required this.id. A default for created must be a compile-time constant, and DateTime.now() is not one, so this.created = DateTime.now() does not compile. Take a nullable parameter and fill the field in the initializer list:
class Record {
final String id;
final DateTime created;
Record({required this.id, DateTime? created})
: created = created ?? DateTime.now();
}
Exercise
Why does Child(this.b) : c = b + 1; compile, but Child(this.b) : c = this.b + 1; does not?
Show answer
In an initializer list, the name b refers to the constructor parameter, which is already available. this.b reads the field through this, and this is not accessible during initialization because the object is not yet fully constructed.