Junior
What is the difference between the keywords final and const in Dart?
sobes.tech AI
Answer from AI
final and const are used to create variables whose values cannot be changed after initialization.
Main differences:
-
Initialization time:
finalis initialized at runtime upon first access.constis initialized at compile-time.
-
Type of values:
finalvariable can hold a value computed at runtime.constvariable must hold a value that can be computed at compile-time (literals, results of constant expressions).
-
Constancy:
final: The variable is constant, but the value it references (if it is an object) can be mutable.const: The variable is constant, and the value it references must also be constant (immutable).
Examples:
// final - initialized at runtime
final DateTime now = DateTime.now(); // Value known only at runtime
// const - initialized at compile-time
const double pi = 3.14; // Value known at compile time
// Using const for lists and maps makes them immutable
const List<int> constantList = [1, 2, 3];
// constantList[0] = 10; // Error! List is immutable
// Using final for lists and maps makes the variable immutable,
// but the contents of the object can be changed (if the object is mutable)
final List<int> finalList = [1, 2, 3];
finalList[0] = 10; // Allowed, since the List itself is mutable
// final with a constant value
final int a = 5; // Allowed, but const is more appropriate
| Initialization | Value requirements | Mutability of the object (if referencing an object) | |
|---|---|---|---|
final |
At runtime | Can be computed at runtime | Can be mutable if the object itself is mutable |
const |
At compile-time | Must be known at compile-time | Must be immutable |