final
- Dart course
- Beginner
- Lesson 8/116
- 4 min
Learn to declare immutable variables with final.
The final keyword
With final you declare a variable that is assigned once and cannot be changed afterwards. For example final pi = 3.14;; then pi = 3; is a compile error.
final is a runtime constant. The value can be computed when the program runs; what matters is that the first value is given. After that it does not change.
final is commonly used for config data, fixed lists and 'set once' logic. Writing final instead of var prevents accidental changes.
Practice Declare with final
Declare a name variable with final (set to Alex) and print it with print.
Starter code
// Declare a final variableSample solution
void main() {
final name = 'Alex';
print(name);
}Expected output
Alex
Difference between final and const
Both final and const create immutable variables, but there is a difference. final sets the value at runtime; const sets it at compile time.
So final now = DateTime.now(); works (the time is read at runtime) but const now = DateTime.now(); is an error; DateTime.now() cannot be known at compile time.
We will see const in detail in the next lesson. For now, know that final is flexible and const is strict.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Runtime constant
____ pi = 3.14;
final pi = 3.14;
Explanation: final is a runtime constant.
2 Can a final variable be reassigned later?
- Yes, same type
- Yes, always
- No, never Correct answer
- Only on first use
Explanation: final is assigned once; it never changes after.
3 final concepts
| Term | Meaning |
|---|---|
final |
Runtime constant |
const |
Compile-time constant |
var |
Mutable |
int |
Integer type |