final and const. While both prevent variable reassignment, they differ fundamentally in their initialization timing, memory allocation, and depth of immutability.
The final Keyword
A final variable is a runtime constant. It can only be set once, but the value does not need to be known until the code executes.
- Initialization: Occurs at runtime.
- Assignment: Single-assignment. Once initialized, the reference cannot be changed.
- Mutability: Shallow immutability. While the variable reference is frozen, the internal state of the object it points to may remain mutable (unless the object class itself is immutable).
The const Keyword
A const variable is a compile-time constant. The value must be completely resolved and frozen before the program runs. const is implicitly final.
- Initialization: Occurs at compile-time.
- Assignment: Must be assigned a constant value (literals, other constants, or results of arithmetic operations on constants) immediately upon declaration.
- Mutability: Deep (transitive) immutability. Both the reference and the object’s internal state are frozen. Attempting to modify the internal state results in a runtime exception.
Canonicalization
Dart canonicalizesconst objects. If two const variables are initialized with the exact same value or object construction, they share the same memory address. This does not apply to final variables.
Class-Level Constants
The behavior of constants changes slightly depending on the scope within a class definition.- Instance Variables: Can be
finalbut cannot beconst. - Static Fields: Can be
static constorstatic final.
Constant Contexts
Theconst keyword can be used on the right side of an assignment to create a constant value, even if the variable holding it is not const.
Master Dart with Deep Grasping Methodology!Learn More





