Sub topic 9
Constant Constructors and Compile-Time Constants
Assume you know basic Dart classes, fields, constructors, and null safety. This chapter focuses on when Dart can create an object before the program runs and how const constructors support that process.
What a compile-time constant is
A compile-time constant is a value that Dart can determine while compiling the program. The value cannot depend on runtime information such as user input, the current time, or a file.
Use const to declare a compile-time constant:
const maxRetries = 3;
const greeting = 'Hello';
const enabledFeatures = ['search', 'sharing'];
void main() {
print(maxRetries);
print(greeting);
print(enabledFeatures);
}A final variable is assigned only once, but its value can be calculated while the program runs:
final startedAt = DateTime.now();startedAt cannot be const because the current time is unknown during compilation.
Defining a constant constructor
A constant constructor is a constructor marked with const. It allows Dart to create constant instances when every argument is also a compile-time constant.
For a class to have a usable constant constructor, its instance fields must be initialized as part of construction and must be final.
class Size {
final double width;
final double height;
const Size(this.width, this.height);
double get area => width * height;
}
void main() {
const screen = Size(1920, 1080);
print(screen.width);
print(screen.area);
}const Size(1920, 1080) is created at compile time. The constructor has no body because constant construction must be fully described by its fields and initializer list.
A constant constructor can also use named parameters and assertions:
class Temperature {
final double celsius;
const Temperature({required this.celsius})
: assert(celsius >= -273.15);
bool get isFreezing => celsius <= 0;
}The assertion rejects temperatures below absolute zero when assertions are enabled.
`const` context
Some language locations provide a const context. In these locations, Dart automatically treats eligible values as constants.
const sizes = [
Size(10, 20),
Size(30, 40),
];The const before the list applies to the list and its constant elements. You can also write const Size(10, 20) explicitly, but it is unnecessary here.
The following expressions are different:
const fixed = Size(10, 20);
final runtimeValue = Size(10, 20);Both variables refer to a Size object, but only fixed must be a compile-time constant. A constant constructor can also create a normal runtime object when called without const.
| Declaration | Compile-time value | Can change fields |
|---|---|---|
| `const point = Size(1, 2)` | Yes | No |
| `final point = Size(1, 2)` | No | No, because fields are final |
| `var point = Size(1, 2)` | No | No, because fields are final |
Canonical constant objects
Dart canonicalizes constant objects. This means equal constant expressions can refer to the same object:
const first = Size(10, 20);
const second = Size(10, 20);
print(identical(first, second)); // trueidentical checks whether two references point to the same object. This behavior can reduce duplicate constant objects, but you should compare values with == when identity is not part of your design.
Choosing `const`
Use a constant constructor when instances are immutable and their values are known before execution. Common examples include dimensions, colors, configuration values, and lightweight value objects.
Do not use const when construction needs runtime data, performs input/output, or depends on mutable state.
Exercise
What is wrong with const now = DateTime.now();, and how could you declare the value instead?
Show answer
DateTime.now() depends on runtime time, so it is not a compile-time constant. Use final now = DateTime.now();.