In Flutter (and Dart), both const and final are used to declare immutable variables, but there are key differences in when and how they are initialized.
Summary of Differences
| Feature | final | const |
|---|---|---|
| Immutability | Single assignment only | Single assignment only |
| When Initialized | At runtime | At compile time |
| Usage | When value is known at runtime | When value is known at compile time |
| Memory | New instance each time | Canonicalized (same instance reused) |
| Can be used with | API responses, dynamic values | Static values like hard-coded literals |
| In Classes | Use final for instance fields | Use const for compile-time constants |
Detailed Explanation
final
- Initialized only once
- Value is set at runtime
- Useful when you don’t know the value until runtime (e.g., API results, user input, DateTime)
final name = 'John';
final currentTime = DateTime.now(); // Allowed
const
- Compile-time constant
- Must be initialized with a value known at compile time
- Uses canonicalization – same object is reused in memory
const pi = 3.14;
const list = [1, 2, 3];
const time = DateTime.now(); // Error: not allowed (runtime value)
const with Widgets
In Flutter UI code, you often use const for widgets to improve performance:
const Text('Hello'); // Widget is created at compile time and reused
This avoids unnecessary rebuilds and improves efficiency.
When to Use What?
| Use case | Keyword to use |
|---|---|
| Value doesn’t change and known early | const |
| Value doesn’t change but known later | final |
| Value changes | No final/const |
