final and const fields
- Dart course
- Intermediate
- Lesson 20/116
- 5 min
Learn immutability with final and const fields.
final fields
A final field can be assigned only once; after assignment it cannot be changed. This is the basic way to build immutable objects.
Example: class Circle { final double radius; Circle(this.radius); }. Here radius is final; its value is set when the constructor runs and cannot be changed afterwards. final fields must be assigned before the constructor completes, so they are initialized via the initializer list or the this.field shortcut. final fits values determined at runtime.
const fields
A const field is a constant known at compile time. It is written with the const keyword and its value must be computable during compilation.
Example: class Circle { final double radius; const Circle(this.radius); static const pi = 3.14; }. Here pi is const; its value is known at compile time. radius is final; each instance can hold a different value. const fields are implicitly final; they also carry the extra condition of being computable at compile time. Use const for fixed values and final for per instance values.
Practice Write Circle with final and const
Define the Circle class; add a final double radius field. Write a const Circle(this.radius) constructor. Add a static const pi = 3.14; constant. Write a double get area => pi * radius * radius; getter. In main, create an instance with const c = Circle(2); and call print(c.area).
Starter code
// Define the Circle class
// Add final radius, const constructor, static const pi and area getter
void main() {
// Create a const Circle(2) instance and print c.area
}Sample solution
// Define the Circle class
class Circle {
final double radius;
const Circle(this.radius);
static const pi = 3.14;
double get area => pi * radius * radius;
}
void main() {
const c = Circle(2);
print(c.area);
}Expected output
12.56
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match final and const
| Term | Meaning |
|---|---|
final |
Set at runtime |
const |
Set at compile time |
immutable |
Unchanging object |
2 Add a const field
class Circle {
final double radius;
const Circle(this.radius);
static ____ pi = 3.14;
}
class Circle {
final double radius;
const Circle(this.radius);
static const pi = 3.14;
}
Explanation: const marks compile time constants.
3 Which is true?
- A final field is set in the constructor, a const field is known at compile time Correct answer
- A const field is set in the constructor, a final field is known at compile time
- final is only used with static fields
- They are the same
Explanation: Both are immutable but assignment time differs: final at runtime, const at compile time.