In Dart, a constant that is computed at runtime cannot be declared using const, because const values must be known and evaluated at compile-time.
So, when we need a value that is determined only during program execution, we use final instead.
1. Using final for runtime constants #
final means the variable’s value can be set only once, but that value can be computed at runtime.
Example:
void main() {
final currentTime = DateTime.now();
print('Current time: $currentTime');
}
Here, DateTime.now() can only be evaluated at runtime, so using const would throw an error.final ensures the value can’t be changed later, maintaining immutability after initialization.
2. Difference between const and final #
| Feature | const | final |
|---|---|---|
| When evaluated | Compile-time | Runtime |
| Mutability | Immutable | Immutable |
| Can depend on runtime values? | ❌ No | ✅ Yes |
| Common use case | Static constants like sizes, colors | Dynamic constants like timestamps, environment configs |
Example comparison:
const pi = 3.14; // Known at compile time
final time = DateTime.now(); // Known only at runtime
3. Real-world example #
In one of my Flutter apps, I used a final variable to store the app’s session start time:
class AppSession {
final startTime = DateTime.now();
void printSessionStart() {
print('Session started at: $startTime');
}
}
This ensured the start time was computed only once when the session began and couldn’t be modified afterward — but it wasn’t a compile-time constant.
4. Challenge faced #
Initially, I mistakenly used const for values that depended on runtime operations like DateTime.now() or Platform.environment.
That caused compile-time errors like:
“Constant expressions must be compile-time constants.”
After understanding this, I switched to final, which fixed the issue.
5. Limitation #
The only limitation with final is that it’s runtime-only — meaning you can’t use it in a const context, like in annotations or as default parameter values.
Summary #
In Dart, if you need a constant value that’s computed during program execution, use
final— notconst.constis for compile-time constants, whilefinalis for runtime constants that you want to set once and never change.
