Sub topic 9
Constant Constructors and Compile-Time Constants
This chapter assumes you can write a generative constructor with initializing formals, use an initializer list, and tell final fields from mutable ones. Here you will see how a const constructor lets Dart build objects at compile time and share one instance between identical values.
final versus const
Both keywords stop a variable from being reassigned, but they differ in when the value is known.
- A
finalvariable is assigned once, at runtime. Its value can come from anywhere, such asDateTime.now()or user input. - A
constvariable must be computed entirely at compile time. The compiler needs to know the value before the program runs.
void main() {
final now = DateTime.now(); // fine: decided at runtime
const limit = 100; // fine: a literal
const doubled = limit * 2; // fine: arithmetic on constants
// const stamp = DateTime.now(); // error: not a constant expression
print('$now $limit $doubled');
}Numbers, strings, booleans, null, and const collections can all appear in constant expressions. Operators and string interpolation over those values also work. Calling an arbitrary function does not.
Declaring a constant constructor
To make your own class usable in constant expressions, put const before the constructor.
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin()
: x = 0,
y = 0;
}Dart enforces these rules on a class with a const constructor:
| Rule | Reason |
|---|---|
| Every instance field is `final`. | A compile-time object can never change afterward. `late final` fields are also rejected. |
| The constructor has no body. | Code in a body would run at runtime. |
| The initializer list contains only constant expressions (and `assert`). | The compiler must be able to evaluate it. |
| A superclass other than `Object` must have a const constructor, and the subclass must call it. | The whole object must be constant. |
| Applied mixins declare no instance fields. | Mixin fields could be mutable. |
If you break a rule, the analyzer reports an error on the constructor declaration itself. You do not have to wait until someone calls it.
A subclass keeps the chain constant by forwarding with super parameters:
class Animal {
final String name;
const Animal(this.name);
}
class Dog extends Animal {
final String breed;
const Dog(super.name, this.breed);
}
void main() {
const rex = Dog('Rex', 'Beagle');
print('${rex.name} ${rex.breed}');
}A const constructor does not force callers to use it as a constant. You can still call Point(1, 2) at runtime and get an ordinary object. The const keyword at the call site makes the difference.
Canonical instances
When you create an object with const, Dart canonicalizes it. Two const expressions with the same class and the same field values produce one shared object in memory.
class Point {
final double x;
final double y;
const Point(this.x, this.y);
}
void main() {
const a = Point(1, 2);
const b = Point(1, 2);
final c = Point(1, 2);
var d = const Point(1, 2);
print(identical(a, b)); // true: same canonical object
print(identical(a, d)); // true
print(identical(a, c)); // false: c was built at runtime
print(a == c); // false: Point does not override ==
}The last line matters. const gives you identity sharing, not value equality. If you want Point(1, 2) == Point(1, 2) to be true for runtime objects, override == and hashCode. Canonicalization is an optimization. It does not replace those overrides.
Notice that const a = Point(1, 2) passes 1 and 2 to double fields. In a constant expression Dart converts the integer literals to doubles, so this compiles.
When an invocation is constant
Dart decides whether an expression creates a constant from the keyword and the surrounding context.
A const context is any place where everything must already be constant. Examples are the initializer of a const variable, the elements of a const list or map, and the arguments of an invocation already written with const. Inside a const context the inner const keywords are optional, and Dart adds them:
class Range {
final int min;
final int max;
const Range(this.min, this.max)
: assert(min <= max, 'min must not exceed max');
bool contains(int value) => value >= min && value <= max;
}
void main() {
const ranges = [Range(0, 1), Range(2, 3)]; // inner const is implicit
print(ranges.length);
final low = int.parse('3');
final runtime = Range(low, 10); // fine: ordinary runtime object
print(runtime.contains(5));
// const bad = Range(low, 10); // error: low is not a constant
try {
ranges.add(Range(4, 5));
} on UnsupportedError {
print('const lists cannot be modified');
}
}Three behaviors show up here:
- The variable
lowisfinal, but notconst, so it cannot be an argument to a const invocation. - An
assertin a const constructor runs at compile time when the call is constant.const Range(5, 1)is a compile error. With a non-const call, the assert runs only in debug mode, at runtime. - A
constcollection is deeply immutable. CallingaddthrowsUnsupportedError.
Where constants are required
Some places accept only constant values. Knowing them helps you read the error messages.
- Default values for optional parameters, such as
void log([Range r = const Range(0, 9)]). - Annotation arguments.
caseexpressions and constant patterns inswitch.- Initializers of
constvariables and ofstatic constfields.
For a constant shared by all instances of a class, use static const. Compare it with static final, which is evaluated lazily at runtime.
class Config {
static const defaultPort = 8080;
static final startedAt = DateTime.now();
const Config();
}static const is the only form valid in const expressions and switch cases. static final is for runtime-computed values.
Why bother: Flutter widgets
Flutter widgets are a typical use of const constructors. Widget classes are immutable, so most of them declare const constructors. When you write const Text('Hello') or const SizedBox(height: 8), the framework gets the same instance on every rebuild. Because the instance is identical, Flutter can skip rebuilding that subtree. This is the reason lints such as prefer_const_constructors exist. They find places where adding const costs nothing and saves work.
Const factory constructors
A factory constructor can be const only if it redirects to another const constructor. It cannot run code or return a cached object.
class Color {
final int value;
const Color(this.value);
const factory Color.red() = _RedColor;
}
class _RedColor extends Color {
const _RedColor() : super(0xFFFF0000);
}
void main() {
const c = Color.red();
print(c.value);
}A caching factory, like the Logger example in the factory constructors chapter, cannot be const because it depends on runtime state.
Common errors
- "Can't define a const constructor for a class with non-final fields." Make the fields
final, or removeconst. - "Arguments of a constant creation must be constant expressions." One argument is a
finalvariable, a function call, or a parameter. Make it a literal or aconstvariable, or dropconstfrom the call. - Expecting
==to be true. Two non-const instances with equal fields are not equal until you override==. - Trying to mutate a const collection. Create a growable copy with
[...constList]orList.of(constList).
Exercise
Given class Tag { final String label; const Tag(this.label); }, which of these lines compile, and what does identical return for the two valid comparisons? (1) const a = Tag('x'); const b = Tag('x'); print(identical(a, b)); (2) final s = 'x'; const c = Tag(s); (3) final d = Tag('x'); print(identical(d, const Tag('x')));
Show answer
Line (1) compiles and prints true, because both const invocations with the same field value share one canonical instance. Line (2) fails, because s is final, not const, so it is not a constant expression. Line (3) compiles and prints false, because d was created at runtime without const, so it is a different object from the canonical constant.
Exercise
A teammate writes class Counter { int count; const Counter(this.count); }. Name the problem and give two ways to fix it.
Show answer
A const constructor requires every instance field to be final, and count is mutable. Fix one: make it final int count; and have code that needs a new value create a new Counter. Fix two: remove const from the constructor if the object has to be mutable.