What are Constants?
A constant is a variable whose value cannot be changed after it is set. Using constants makes your code safer (prevents accidental modification), more readable (meaningful names), and sometimes more performant (compile-time constants).
The final Keyword
A final variable can be set only once, at runtime. Its value is determined when the program runs.
final String name = 'Alice';
final int year = DateTime.now().year; // runtime value OK
// name = 'Bob'; ← ERROR: can't change a final variable
final List<int> numbers = [1, 2, 3];
numbers.add(4); // ✅ OK — the list itself can be modified
// numbers = [5, 6]; ← ERROR — can't reassign the reference
The const Keyword
A const variable is a compile-time constant. Its value must be known at compile time (cannot use runtime values like DateTime.now()).
const double pi = 3.14159;
const int maxItems = 100;
const String appName = 'MyApp';
// const int year = DateTime.now().year; ← ERROR (runtime value)
const List<int> primes = [2, 3, 5, 7, 11];
// primes.add(13); ← ERROR — const list is immutable
final vs const
| Feature | final | const |
| When value is set | Runtime | Compile time |
| Can use runtime values | ✅ Yes | ❌ No |
| Reassignable | ❌ No | ❌ No |
| Object contents mutable | ✅ Yes (list/map) | ❌ No (deeply immutable) |
| Memory sharing | Per instance | Shared canonical |
const Objects & Lists
// const list — deeply immutable
const List<String> colors = ['red', 'green', 'blue'];
// colors.add('yellow'); ← ERROR: Unsupported operation
// const map
const Map<String, int> statusCodes = {
'ok': 200,
'notFound': 404,
'error': 500,
};
print(statusCodes['ok']); // 200
Full Example
void main() {
const double pi = 3.14159;
final double radius = 5.0; // could be user input
final double area = pi * radius * radius;
print('Pi: $pi');
print('Radius: $radius');
print('Circle area: $${area.toStringAsFixed(2)}');
const String appVersion = '1.0.0';
final DateTime launchDate = DateTime.now();
print('App: $appVersion launched at $launchDate');
}
Output:
Pi: 3.14159
Radius: 5.0
Circle area: 78.54
App: 1.0.0 launched at 2024-01-15 10:30:00.000
⚠️ Common Mistakes
- Using
const with a runtime value like DateTime.now() — use final instead.
- Trying to modify a
const list — all elements are immutable.
- Confusing "the reference can't change" (final) with "the object can't change" (const).
🧠 Quiz
1. Which keyword is used for compile-time constants?
- A) final
- B) static
- C) const ✅
- D) readonly
2. Can you add items to a final List?
- A) No
- B) Yes ✅
- C) Only if the list is empty
- D) Only with special syntax
Summary
Use final for variables set once at runtime, and const for compile-time constants. final allows mutable objects (you can modify a final list's contents), while const makes everything deeply immutable. Prefer const when the value is known at compile time for better performance.