Sub topic 6
Initializer Lists and Final Fields
Assume you know basic Dart classes, constructors, types, and null safety. This chapter focuses on how constructors initialize final fields before the constructor body runs.
Why initialization order matters
A final field can be assigned only once. A constructor must assign every non-nullable final field before its body starts. Dart provides two useful ways to do this:
- An initializing formal parameter assigns a parameter directly to a field.
- An initializer list assigns fields or calculates values before the constructor body.
The initializer list follows the constructor signature after a colon:
ClassName(arguments)
: field = value,
anotherField = otherValue {
// Constructor body
}Initializer expressions run from left to right. The constructor body runs only after all fields have been initialized.
Initializing formals
When a parameter has the form this.fieldName, Dart assigns the argument to that field automatically.
class User {
final String name;
final int age;
User(this.name, this.age);
}This is equivalent to receiving ordinary parameters and assigning them manually, but it is shorter and makes the field initialization clear.
Initializer lists
Use an initializer list when a field needs a calculated value, validation, or data extracted from another object.
class Rectangle {
final double width;
final double height;
final double area;
Rectangle(this.width, this.height)
: assert(width >= 0),
assert(height >= 0),
area = width * height;
String description() => '$width x $height = $area';
}
void main() {
final rectangle = Rectangle(4, 3);
print(rectangle.description());
}The assert expressions check constructor arguments in debug mode. The area field is calculated before the constructor body would run. Because area is final, calculating it in the initializer list is appropriate.
A field may depend on constructor parameters, but do not rely on another instance field being initialized earlier. Use the original parameters or a helper function instead.
Named constructors and parsed values
An initializer list is useful for named constructors that create an object from another representation.
class Point {
final double x;
final double y;
const Point(this.x, this.y);
Point.fromJson(Map<String, Object?> json)
: x = (json['x'] as num).toDouble(),
y = (json['y'] as num).toDouble();
}
void main() {
final point = Point.fromJson({'x': 2, 'y': 5});
print('(${point.x}, ${point.y})');
}The casts tell Dart that the values are numbers. Calling toDouble() gives both fields the declared double type.
Exercise
Why does Rectangle calculate area in its initializer list instead of assigning area in the constructor body?
Show answer
Because area is a final field, and it must be assigned before the constructor body runs.