In Dart, both final
and const
are used to create variables whose values cannot be changed after initialization (immutable). However, there are important differences between them.
1. Time of Value Assignment
final
→ Value is determined at runtime (run-time constant). It can come from calculations or inputs known only when the program runs.const
→ Value must be known at compile-time (compile-time constant). Cannot depend on values computed at runtime.
// Allowed: runtime value
final currentTime = DateTime.now();
// ERROR: must be compile-time constant
const currentTimeConst = DateTime.now();
2. Level of Immutability
final
→ The variable itself cannot be reassigned, but the content of the object it references can be changed if it's mutable.const
→ The value and the object are deeply immutable. Const objects are also canonicalized (all const objects with the same value point to the same memory instance).
final listFinal = [1, 2, 3];
listFinal.add(4); // Allowed, list is mutable
// listFinal = [5, 6]; // ERROR
const listConst = [1, 2, 3];
// listConst.add(4); // ERROR, immutable
3. Usage in Classes
final
→ Can be used for instance variables set once, often via constructor.const
→ Only allowed for:static const
(class-level constants)const
constructors for immutable objects
class Person {
final String name; // set via constructor
static const maxAge = 150; // compile-time constant
Person(this.name);
}
4. Quick Comparison Table
Aspect | final |
const |
---|---|---|
Evaluation Time | Runtime | Compile-time |
Mutable Object Content | Yes (if object is mutable) | No |
Usage in Classes | Instance variables | Static const / const constructors |
Canonicalization | No | Yes |
5. Flowchart: When to Use final
vs const
If Blogger supports Mermaid.js, you can embed this diagram:
flowchart TD
A[Do you know the value at compile-time?] -->|Yes| B[Use const]
A -->|No| C[Use final]
B --> D[Value never changes & deeply immutable]
C --> E[Value set at runtime, but variable cannot be reassigned]
If Blogger does not support Mermaid.js, here’s the simplified logic:
- If the value is known before the program runs → Use const
- If the value is known only when the program runs → Use final
0 Comments:
Post a Comment