final variable creates a single-assignment binding that is initialized at runtime. Once a value is assigned to a final variable, the reference cannot be changed, enforcing immutability on the variable binding itself.
Syntax and Declaration
A variable is declared final by prepending thefinal keyword. Type annotation is optional; if omitted, the type is inferred from the assigned value.
Initialization Mechanics
Unlikeconst, which requires compile-time constants, final variables are evaluated and initialized at runtime. This allows the assignment of values that are calculated during program execution.
final variable must be initialized exactly once. If the compiler cannot guarantee that the variable is initialized before it is used, it raises a static analysis error.
Reference Immutability vs. Object Mutability
Thefinal keyword enforces immutability on the reference, not necessarily on the object being referenced.
- Immutable Reference: You cannot reassign the variable to a new object.
- Mutable State: If the referenced object is mutable (e.g., a
Listor a class with non-final fields), its internal state can still be modified.
Class Instance Variables
When a field within a class is declaredfinal, it must be initialized before the constructor body executes. This can be achieved via:
- Inline initialization at the point of declaration.
- Initializing formal parameters.
- An initializer list.
Late Initialization
If afinal variable cannot be initialized at declaration time but is guaranteed to be initialized before usage, the late modifier can be combined with final.
Master Dart with Deep Grasping Methodology!Learn More





