Dart Data Types
A data type is the kind of a stored value. Dart has types for whole numbers, decimal numbers, text, and truth values.
One value of each type
int holds a whole number and double holds a decimal number. String holds text and bool holds a truth value.
void main() {
int whole = 4;
double price = 2.5;
String word = 'cup';
bool ready = true;
print(whole);
print(price);
print(word);
print(ready);
}A value that does not match the type
The annotation int asks for a whole number, and the text value does not fit. Dart refuses to run the program.
void main() {
int score = 'high';
print(score);
}A decimal keeps its point
height holds the double value 2.0. The output keeps the decimal point and shows 2.0.
void main() {
double height = 2.0;
print(height);
}Example
void main() {
int age = 20;
double height = 1.8;
String city = 'York';
bool member = true;
var visits = 3;
print(age);
print(height);
print(city);
print(member);
print(visits);
}Key points
- int is a whole number type.
- double is a number type with a decimal part.
- String is a text type.
- bool is a type with the two values true and false.
- A type annotation writes the type just before the name.
- Dart can also pick the type from the value when no annotation is written.
In this example, age carries the annotation int and holds 20. height carries the annotation double and holds 1.8. city carries the annotation String and holds York. member carries the annotation bool and holds true. visits has no annotation, so its type follows from the value 3. The print lines show the five values in that order.
Note
The names int, double, and bool start with a small letter, and String starts with a capital letter.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Which type holds the values true and false?