Sub topic 7
Initializing fields: required parameters and initializer lists
This chapter assumes you know Dart classes and constructors, and the difference between T and T? from the earlier chapters. You should also be able to run code with dart run or in DartPad.
The rule: every field needs a value before the body runs
A non-nullable field cannot hold null, so Dart must be sure it has a real value before any code can read it. The compiler enforces this at the end of the initialization phase of a constructor, which comes before the constructor body { ... } starts.
A nullable field has an implicit default of null, so it needs no initialization. A non-nullable field has no such default.
class Broken {
String name; // error: non-nullable instance field 'name' must be initialized
int? age; // fine: defaults to null
}Dart reports this error at the field (or at the constructor, if the class declares one that leaves the field unset). Assigning in the body does not fix it, because the body runs too late:
class StillBroken {
String name;
StillBroken(String n) {
name = n; // too late: 'name' must be set before the body starts
}
}You have several ways to give the field a value in time. The rest of this chapter covers them in order.
Initializing formals
The shortest form is an initializing formal, a parameter written as this.field. Dart copies the argument into the field during the initialization phase.
class Point {
final int x;
final int y;
Point(this.x, this.y);
}Because the parameter type is taken from the field, x and y here are non-nullable int parameters. Callers cannot pass null, and they cannot omit the arguments.
Required named parameters
Named parameters are optional by default. If a named parameter has a non-nullable type, no default, and is not required, Dart reports an error. The parameter would silently be null when the caller omits it, and that is not allowed for a non-nullable type.
class User {
final String name;
final String? email;
User({required this.name, this.email});
}
void main() {
final user = User(name: 'Ada');
print(user.email ?? 'no email'); // no email
// User(); // compile-time error: the named parameter 'name' is required
}The pattern is: mark the values that must exist as required and non-nullable, and declare the genuinely optional ones as nullable. The constructor signature then documents which values are mandatory, and the compiler checks every call site.
Default values
A default value is the third option. The parameter is optional, but it is never null.
class Settings {
final String theme;
final int fontSize;
final String? locale;
Settings({this.theme = 'light', this.fontSize = 14, this.locale});
}
void main() {
final s = Settings(fontSize: 18);
print('${s.theme} ${s.fontSize} ${s.locale}'); // light 18 null
}Defaults must be compile-time constants. For positional optional parameters, put them in square brackets: Point([this.x = 0, this.y = 0]).
| Situation | Declare it as |
|---|---|
| The caller must always supply a value | Non-nullable field, `required` named parameter or plain positional parameter |
| A sensible fixed fallback exists | Non-nullable field with a constant default |
| The absence of a value is meaningful | Nullable field (`String?`), no default needed |
| The value is derived from other values | Initializer list (next section) |
| The value is expensive and not always needed | `late` field (covered in the next chapter) |
Field initializers
You can also give a field a value where you declare it. This runs before any constructor parameters are available, so it cannot refer to them or to this.
class Counter {
int count = 0;
final List<String> log = [];
}Such a class needs no constructor at all, because every field already has a value.
Initializer lists
Sometimes a field depends on parameters but should not be a parameter itself. An initializer list sits between the constructor's parameters and its body, after a colon, and assigns fields before the body runs.
class Rect {
final double width;
final double height;
final double area;
Rect(this.width, this.height)
: area = width * height,
assert(width >= 0 && height >= 0, 'sizes must not be negative');
}
void main() {
final r = Rect(3, 4);
print(r.area); // 12.0
}Three rules apply to initializer lists:
- Entries are separated by commas. Each is a field assignment, an
assert, asuper(...)call, or athis(...)redirect. - Inside the list, a bare name such as
widthrefers to the parameter. You cannot usethis, so you cannot read other fields or call instance methods. - You can call top-level or
staticfunctions, which makes initializer lists a good place for light computation.
class Tag {
final String id;
final String label;
Tag(String raw)
: id = _clean(raw),
label = 'tag:${_clean(raw)}';
static String _clean(String s) => s.trim().toLowerCase();
}Here _clean is a static method, so it is legal in the initializer list. An instance method would be rejected, because the object is not fully built yet.
Order of initialization
When you create an object, Dart runs these steps in a fixed order.
Two consequences follow. First, this is only usable in step 4, so only the body can call instance methods. Second, a final field can be assigned only in steps 1 or 2, never in the body.
Initializing with a superclass
A subclass must make sure its superclass is initialized too. If the superclass constructor takes arguments, forward them. Since Dart 2.17 you can use super parameters, which work like initializing formals.
class Animal {
final String name;
Animal(this.name);
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
}You can also write the explicit super(...) call at the end of the initializer list. Put it last, because Dart requires it there.
class Puppy extends Animal {
final int ageInWeeks;
Puppy(String name, int weeks)
: ageInWeeks = weeks,
super(name.toUpperCase());
}Named and redirecting constructors
Each constructor must independently initialize every non-nullable field. A redirecting constructor delegates this job to another constructor with this(...), and it can have no body and no other initializers.
class Vec {
final int x;
final int y;
Vec(this.x, this.y);
Vec.zero() : this(0, 0);
Vec.fromList(List<int> v) : x = v[0], y = v[1];
}
void main() {
print(Vec.zero().x); // 0
print(Vec.fromList([5, 6]).y); // 6
}If you add a second constructor and forget a field, the compiler reports the missing initialization on that constructor, not on the first one.
Common errors
- "Non-nullable instance field must be initialized." No constructor path gives the field a value. Add
this.field, a default, an initializer, or make the field nullable. - "The parameter can't have a value of 'null' because of its type." A non-nullable named parameter has no default and is not
required. Addrequiredor a default. - Assigning a
finalfield in the body. Move the assignment into the initializer list. - Using
thisor an instance method in the initializer list. Use astaticfunction, or restructure so the computation happens in a factory constructor. - Making everything nullable to silence the compiler. This pushes
nullchecks into every use. If a value is always present after construction, keep it non-nullable and require it.
A complete example
This program combines required parameters, a default, an initializer list with an assert, and a nullable optional field.
class Order {
final String id;
final int quantity;
final double unitPrice;
final double total;
final String? note;
Order({
required this.id,
this.quantity = 1,
required this.unitPrice,
this.note,
}) : assert(quantity > 0, 'quantity must be positive'),
total = quantity * unitPrice;
@override
String toString() => 'Order $id: $total${note == null ? '' : ' ($note)'}';
}
void main() {
print(Order(id: 'A1', unitPrice: 2.5)); // Order A1: 2.5
print(Order(id: 'B2', quantity: 4, unitPrice: 2.5, note: 'gift'));
// Order B2: 10.0 (gift)
}Note that quantity in the initializer list is the parameter, which already holds the default of 1 when the caller omits it. Also note that asserts run only in debug mode (for example, dart run --enable-asserts), so do not rely on them for validation in release builds.
Exercise
This class does not compile. Name two different ways to fix it without making title nullable.
class Note {
String title;
Note();
}
Show answer
Make the value required: Note(this.title); or Note({required this.title});. Or give it a default, either at the field (String title = 'Untitled';) or in the constructor (Note({this.title = 'Untitled'});). Computing it in an initializer list, such as Note() : title = 'Untitled';, also works.
Exercise
A class has final double area; and a constructor Circle(this.radius) { area = 3.14159 * radius * radius; }. Why does this fail, and how do you fix it?
Show answer
A final field must be assigned during the initialization phase, before the body runs, so assigning it in the body is an error. Move the computation into an initializer list: Circle(this.radius) : area = 3.14159 * radius * radius;.