Dart Constants
A constant is a named value that never changes. Dart uses the keyword const for a constant.
A const value shown
const gives daysInWeek the value 7. print shows the stored number.
void main() {
const daysInWeek = 7;
print(daysInWeek);
}A const text value
const can also hold a text value. print shows the stored greeting.
void main() {
const greeting = 'Hello';
print(greeting);
}const and final side by side
limit holds a const value and score holds a final value. Each print shows one stored value on its own line.
void main() {
const limit = 5;
final score = 10;
print(limit);
print(score);
}Changing a const value fails
The last line tries to give limit a new value. Dart stops and names const in its error.
void main() {
const limit = 5;
limit = 6;
}Example
void main() {
const maxScore = 100;
final player = 'Ana';
print(player);
print(maxScore);
}Key points
- const is a keyword that names a value fixed before the program runs.
- Use = to give a constant its value.
- Use a constant name in print to show its value.
- A const value must be known before the program runs.
- A final value is set once when the program runs.
In this example, const maxScore holds the fixed value 100. final player holds the text Ana. The first print shows Ana. The second print shows 100.
Note
const fits a value that is already fixed, like the number of days in a week.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Which keyword names a value that is known before the program runs and never changes?