const constructor
- Dart course
- Intermediate
- Lesson 4/116
- 5 min
Learn compile-time objects with const constructors.
const constructor
A const constructor produces a compile time constant instance. The constructor is prefixed with const and all fields must be final.
Example: class Point { final double x; final double y; const Point(this.x, this.y); }. Here const Point(0, 0) returns the same canonical instance on every call; this saves memory and speeds up equality checks. The constructor can be called without const too; then no compile time constant is produced. This shape is used heavily in the Flutter widget tree.
Canonical instances
Two const Point(0, 0) calls refer to the same instance; Dart makes them canonical. The identical(a, b) function returns true; the == operator also returns true.
Example: const a = Point(0, 0); const b = Point(0, 0); print(identical(a, b)); prints true. This means no new object is created for the same constant value; it brings memory and speed gains in large object graphs. If you omit const at the call site, a new instance is produced each time and canonicalness is lost.
Practice Add a const constructor to Point
Define the Point class; add final double x and final double y fields. Write a const Point(this.x, this.y) constructor. In main, create an instance with const p = Point(0, 0); and call print(p.x).
Starter code
// Define the Point class
// Add final x and y fields
// Write the constructor with the const prefix
void main() {
// Create the const p = Point(0, 0) instance and print p.x
}Sample solution
// Define the Point class
class Point {
final double x;
final double y;
const Point(this.x, this.y);
}
void main() {
const p = Point(0, 0);
print(p.x);
}Expected output
0.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What fields does a const constructor require?
- Only static fields
- Only late fields
- Any field type
- Only final fields Correct answer
Explanation: A const constructor requires all fields to be final.
2 Match the const constructor parts
| Term | Meaning |
|---|---|
const Point |
Constructor prefix |
final |
Field keyword |
identical(a, b) |
Same instance query |
3 Add the const keyword
class Point {
final double x;
final double y;
____ Point(this.x, this.y);
}
class Point {
final double x;
final double y;
const Point(this.x, this.y);
}
Explanation: The const keyword makes the constructor a compile time constant.