Dart Variables
A variable is a named stored value in a program. Dart uses var for a value that can change and final for a value that cannot change.
A var value shown
var gives days the value 7. print shows the stored number.
void main() {
var days = 7;
print(days);
}Changing a var
The two print lines show count before and after the change. The count grows from 1 to 2 in the output.
void main() {
var count = 1;
print(count);
count = 2;
print(count);
}A final value shown
final gives city the text value York. print shows the stored text.
void main() {
final city = 'York';
print(city);
}Changing a final value fails
The last line tries to give limit a new value. Dart stops and names final in its error.
void main() {
final limit = 5;
limit = 6;
}Example
void main() {
var score = 10;
print(score);
score = 15;
print(score);
}Key points
- var is a keyword that names a value that can change.
- final is a keyword that names a value that cannot change.
- Use = to give a name its value.
- Use a name in print to show the value it holds.
- A final value is set once and then stays the same.
In this example, var score starts with the value 10. The first print shows 10. The next line changes score to 15. The last print shows 15.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Which keyword names a value that can change?