Variables, Types, and Inference
A variable is a name that points to a piece of information your program keeps in memory — like a labeled box. A type describes what kind of information the box holds: text, a whole number, a decimal number, or a yes/no value.
Dart cares about types, but it does not make you write them everywhere. This chapter shows how Dart stores values, when you write types yourself, and when the language figures them out for you.
The Basic Types You Will Use Most
These four types cover most everyday code:
| Type | Holds | Example |
|---|---|---|
| `String` | Text | `'Ada'` |
| `int` | Whole numbers | `1815` |
| `double` | Decimal numbers | `9.5` |
| `bool` | True or false | `true` |
void main() {
String name = 'Ada';
int year = 1815;
double score = 9.5;
bool active = true;
print('Name: $name, Year: $year, Score: $score, Active: $active');
}The $name inside the text is string interpolation: Dart replaces it with the value of the variable. It saves you from gluing text together by hand.
Letting Dart Infer the Type
When you give a variable a starting value, Dart can often work out the type by itself. This is called type inference. You write var — short for "variable" — and Dart picks the type from the value on the right.
void main() {
var inferred = 'type inferred from initializer';
print(inferred);
}Here Dart decides inferred is a String, because '...' is text. Once the type is chosen, it is locked in. You cannot later put a number into that variable — Dart will report an error before the program even runs. That early warning is the main benefit of types: mistakes surface when you write code, not when users run it.
Two Special Modifiers: final and const
Sometimes a variable should never change after it is set. Use final for a value set once at runtime, or const for a value known before the program runs.
void main() {
final greeting = 'Hello, $name!';
const secondsPerHour = 3600;
print(greeting);
print(secondsPerHour);
}Trying to assign a new value to greeting later is an error. Reaching for final by default is a good habit — it prevents accidental changes.
Exercise
What type does Dart infer for var count = 10;, and can you later assign 'ten' to it?
Show answer
Dart infers int. No — assigning a String to an int variable is a type error Dart catches before the program runs.
Exercise
What is the difference between final and const?
Show answer
final means set once at runtime; const means the value is fixed before the program ever runs. Both prevent later reassignment.
Spotted a mistake, or code that does not work?