Data Types and Type Inference
Prerequisites: Variables: var, final, and const
Every value in Dart has a type. The core types:
| Type | Example | Used for |
|---|---|---|
int |
42, -7 |
Whole numbers |
double |
3.14 |
Numbers with a decimal point |
num |
42 or 3.14 |
Either kind of number |
String |
'hello' |
Text |
bool |
true, false |
Yes/no values |
List, Set, Map |
[1, 2] |
Collections (covered later) |
Type inference
Dart works out the type from the value:
void main() {
var count = 10;
var price = 9.99;
var title = 'Dart';
var ready = true;
print(count.runtimeType);
print(price.runtimeType);
print(title.runtimeType);
print(ready.runtimeType);
}
int
double
String
bool
Type annotations
You can write the type instead of var, or after final:
int score = 100;
double ratio = 3; // an int literal is accepted: stored as 3.0
final String name = 'Ada';
Annotations are common for function parameters and class fields, and whenever they make code clearer.
Types are fixed
A variable keeps its type. var level = 1; makes level an int, so
this fails:
void main() {
var level = 1;
level = 'two';
}
hello.dart:3:11: Error: A value of type 'String' can't be assigned to a variable of type 'int'.
Everything is an object
In Dart, every value — even a number or null — is an object with
methods: (-5).abs(), 3.7.round(), 'dart'.toUpperCase().
Dart also has dynamic, which turns off type checking for a variable.
Avoid it — it throws away the safety the compiler gives you.