Sub topic 2
Initializer lists and final fields
This chapter assumes you know basic Dart syntax, null safety (nullable and non-nullable types), and how to create objects and call methods.
Initializer lists and final fields
A final field is set once and never changes. Dart requires every final field to have a value before the constructor body runs. An initializer list, written after a colon (:), sets those fields before the body runs.
class Circle {
final double radius;
final double area;
Circle(double r)
: radius = r,
area = 3.14159 * r * r;
}
void main() {
final c = Circle(2);
print(c.area); // 12.56636
}Named constructors
A named constructor is a second constructor with a name after the class name, such as Point.origin. A class can have several constructors.
Redirecting constructors
A redirecting constructor calls another constructor of the same class with this(...). It has no body of its own.
Constant constructors and compile-time constants
A const constructor creates objects whose values are fixed at compile time. Identical const objects are reused, so they are the same instance.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
const Point.origin() : this(0, 0);
}
void main() {
print(identical(const Point(1, 2), const Point(1, 2))); // true
print(identical(const Point.origin(), const Point(0, 0))); // true
}Factory constructors
A factory constructor is declared with factory. It can return an existing instance instead of always creating a new one. The following class caches loggers by name.
class Logger {
static final Map<String, Logger> _cache = {};
final String name;
factory Logger(String name) =>
_cache.putIfAbsent(name, () => Logger._internal(name));
Logger._internal(this.name);
}Inheritance, super, and super parameters
A subclass uses extends to inherit from a superclass. A super parameter, written super.name, forwards an argument to the superclass constructor. Use super.method() to call the superclass version of an overridden method.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
@override
String describe() => '${super.describe()} ($breed)';
}
void main() {
print(Dog('Rex', 'Collie').describe()); // Animal Rex (Collie)
}Exercise
Why does Circle set area in an initializer list instead of in the constructor body?
Show answer
A final field must have a value before the body runs. The initializer list runs first, so the field is set in time. Assigning it in the body would be a compile error.