Sub topic 6
Initializer lists and final fields
This chapter assumes you know how to declare a class with fields and write a basic generative constructor with this.x parameters. It also assumes you understand null safety, in particular that a non-nullable field must hold a value. The chapter covers how Dart sets final fields, what an initializer list is, and when each initialization form runs.
Why final fields need special handling
A final field can be assigned exactly once. A non-nullable field must also hold a value before any code can read it. Dart combines these two rules and requires every final field to be set before the constructor body starts. The body of a constructor is the block in braces after the parameter list. By the time it runs, the object already exists and you can use this, so all final fields must be set by then.
Assigning a final field inside the body is a compile-time error, because the field is already considered set. The same applies to a non-nullable field with no initial value. The initializer list exists to solve this problem.
Three places to set a field
Dart gives you three places to give a final field its value before the body runs.
| Where | Syntax | Typical use |
|---|---|---|
| Field declaration | `final int a = 1;` | A fixed default that does not depend on arguments |
| Initializing formal | `Point(this.x, this.y);` | Store an argument unchanged |
| Initializer list | `Point.origin() : x = 0, y = 0;` | Compute, convert, or validate before storing |
You can mix these in one constructor. A field must still be set exactly once, so you cannot use this.x and also assign x in the initializer list.
Initializer list syntax
An initializer list sits between the parameter list and the body. It starts with a colon and holds comma-separated entries. Each entry is a field assignment, an assert, or a call to a superclass constructor.
class Point {
final double x;
final double y;
Point(this.x, this.y);
Point.fromJson(Map<String, Object?> json)
: x = (json['x'] as num).toDouble(),
y = (json['y'] as num).toDouble();
@override
String toString() => 'Point($x, $y)';
}
void main() {
final p = Point.fromJson({'x': 3, 'y': 4.5});
print(p);
}The code prints Point(3.0, 4.5). The JSON value 3 is an int, and the initializer list converts it to a double before the field is set. An initializing formal could not do this conversion, because it stores the argument as it arrives.
The left side of each entry is the field name. The right side is an ordinary expression that can use the constructor's parameters. This is why the list is useful for computing derived values.
Derived fields and validation
Because the list can run expressions, one field can be computed from the parameters. An assert can check them first.
class Range {
final int start;
final int end;
final int length;
Range(this.start, this.end)
: assert(start <= end, 'start must not exceed end'),
length = end - start;
}
void main() {
final r = Range(2, 10);
print(r.length);
}This code prints 8. Here start and end use initializing formals, and length is computed from them. Inside the initializer list, the name end refers to the constructor parameter, which is in scope there.
You can read the parameters and call functions, but you cannot read this. You cannot call an instance method or read another field through this, because the object is not ready yet. Static methods and top-level functions are fine.
class Temperature {
final double celsius;
final double fahrenheit;
Temperature(this.celsius) : fahrenheit = _toFahrenheit(celsius);
static double _toFahrenheit(double c) => c * 9 / 5 + 32;
}The _toFahrenheit helper is static, so the list may call it. An instance method with the same body would be rejected.
Order of execution
The order of events matters when constructors have side effects or when a class has a superclass. Dart runs the steps in this order:
- Field declarations that have initializers, such as
final int a = 1;. - The initializer list of the constructor being called, from left to right.
- The superclass constructor, including its own initializer list and body.
- The body of the constructor being called.
The following program prints each step so you can see the order.
class Base {
Base() {
print('Base body');
}
}
int trace(String label, int value) {
print('initializing $label');
return value;
}
class Child extends Base {
final int a = trace('a (declaration)', 1);
final int b;
final int c;
Child(int b, int c)
: b = trace('b', b),
c = trace('c', c),
super() {
print('Child body');
}
}
void main() {
Child(2, 3);
}The output is:
initializing a (declaration)
initializing b
initializing c
Base body
Child bodyThe subclass fields are set before the superclass constructor runs. This is the reverse of some other languages. It is why a superclass constructor that calls an overridden method sees the subclass's final fields already set, though the subclass body has not run.
The superclass call must be the last entry in the list. If you omit it, Dart calls the superclass's unnamed constructor with no arguments, and that constructor must exist. If the superclass has only constructors that require arguments, you must call one explicitly. Chapter 11 covers super parameters, which shorten this.
Every constructor must set every final field
Each generative constructor is responsible for setting all final fields that have no declaration initializer. If a class has three constructors, each one must cover each field, either through a formal, the list, or a redirect to another constructor. A constructor that misses one is a compile-time error that names the field.
This is the main benefit of the rule. After a constructor finishes, no final field is ever unset. You never need a null check for a field that is not nullable.
What the list cannot do
The list holds expressions only, not statements. You cannot write if blocks, loops, or local variables in it. A few tools help you work within this limit:
- Use the conditional operator and
??for simple choices:label = name ?? 'unnamed'. - Move longer logic into a static method or a top-level function, and call it from the list.
- Switch to a factory constructor when you need statements, early returns, or error handling. A factory computes values in its body and then calls a generative constructor.
- Use
late finalwhen a value depends on other fields.
A late final field with an initializer runs lazily on first read. It may use this, because the object is complete by then.
class Report {
final List<int> values;
late final int total = values.fold(0, (sum, v) => sum + v);
Report(this.values);
}
void main() {
final r = Report([1, 2, 3]);
print(r.total);
}This code prints 6. The sum is computed the first time total is read and cached afterward. The cost is that a late field moves the guarantee from compile time to run time. Reading it before it can be computed fails at run time, not at compile time.
Common mistakes
- Assigning in the body.
Point(double x, double y) { this.x = x; }fails forfinalfields. Move the assignment into the list. - Using
thisin the list. An expression such asy = this.x * 2is an error. Use the parameter name instead, or compute the value from the arguments. - Setting a field twice. Using
this.xin the parameters andx = ...in the list is an error. - Forgetting the comma. Entries are separated by commas, with no semicolon until the end of the constructor.
- Missing super arguments. If the superclass has no zero-argument unnamed constructor, add an explicit
super(...)entry at the end of the list.
Exercise
A class Rectangle has final double width, final double height, and final double area. Write its constructor so that area is computed from the arguments, and so that debug builds reject a negative width or height. Which part of the constructor handles each requirement, and why can't the body set area?
Show answer
Use Rectangle(this.width, this.height) : assert(width >= 0 && height >= 0, 'sizes must not be negative'), area = width * height;. The initializing formals store width and height, the assert entry in the initializer list performs the debug check, and the area = width * height entry computes the derived field. The body cannot set area because area is final and non-nullable, so it must already be set when the body starts. Assigning it in the body is a compile-time error.
Exercise
A class Child extends Base declares final int a = log('a');, and its constructor is Child() : b = log('b'), super() { log('body'); }, where Base's constructor body calls log('base'). In what order are the messages logged?
Show answer
The order is a, b, base, body. The field declaration initializer runs first, then the initializer list entry b, then the superclass constructor with its body, and finally the body of the Child constructor.