Dart
Initializer list
Learn field initialization with the initializer list.
Initializer list
An initializer list assigns values to fields before the constructor body runs. It starts with a colon and holds comma separated assignments: : width = size, height = size.
Example: Rectangle.square(double size) : width = size, height = size;. Here width and height are set before the body runs. Since final fields cannot be changed inside the body, the initializer list is the clean way to assign them. The list runs before the body, so doing calculations here is safer.
final fields and the initializer list
Fields marked final may be assigned only once; the assignment must happen before the constructor completes. The initializer list is the cleanest way to meet this requirement.
Example: class Rectangle { final double width; final double height; Rectangle(this.width, this.height); Rectangle.square(double size) : width = size, height = size; }. The square named constructor gives both final fields their values inside the initializer list. Even with an empty body, the statement ends with a semicolon. This shape lets fields produce immutable objects.
Exercise Write the Rectangle.square constructor
Define a class named Rectangle. Add final double width and final double height fields. Write the default constructor Rectangle(this.width, this.height). Add the named constructor Rectangle.square(double size) : width = size, height = size;. In main, create an instance with var r = Rectangle.square(5); and call print(r.width).
Show example solution
// Define the Rectangle class
class Rectangle {
final double width;
final double height;
Rectangle(this.width, this.height);
Rectangle.square(double size) : width = size, height = size;
}
void main() {
var r = Rectangle.square(5);
print(r.width);
}
Test yourself
-
Match the initializer list parts
- :
- List start
- width = size
- Assignment
- final
- Immutable field keyword
-
Add the colon
class Rectangle {
final double width;
final double height;
Rectangle.square(double size)____ width = size, height = size;
}
Show answer
class Rectangle {
final double width;
final double height;
Rectangle.square(double size): width = size, height = size;
}
-
Which is valid initializer list syntax?
- Rectangle.square(double size) { width = size; height = size; }
- Rectangle.square(double size) => width = size, height = size;
- Rectangle.square(double size) : width = size, height = size;
- Rectangle.square(double size) where width = size, height = size;
Show answer
Rectangle.square(double size) : width = size, height = size; — The colon separates the initializer list from the body; the comma divides assignments.
Next lesson: const constructor