Dart Nullable Types
A nullable type is a type that can hold null. null is a value that means no value at all.
A nullable value that holds null
missing has the type int? and no starting value. print shows the word null.
void main() {
int? missing;
print(missing);
}A nullable value that holds a number
score has the type int? and the value 5. print shows the stored number.
void main() {
int? score = 5;
print(score);
}A value that changes to null
city first holds a text value and then holds null. The two print lines show York and then null.
void main() {
String? city = 'York';
print(city);
city = null;
print(city);
}A non-null type at work
name has the type String with no question mark. print shows the stored text.
void main() {
String name = 'Ana';
print(name);
}Giving null to a non-null type fails
The String type has no question mark, so it cannot hold null. The compiler stops and reports the mismatch.
void main() {
String name = null;
print(name);
}Example
void main() {
String? city;
print(city);
city = 'York';
print(city);
}Key points
- A type written with ? can hold null.
- A type written without ? cannot hold null.
- String? can hold a text value or null.
- int? can hold a whole number or null.
- A nullable variable with no starting value holds null.
In this example, city has the type String? and starts with no value. The first print shows null. The next line gives city the value York. The last print shows York.
Note
The question mark belongs to the type, not to the variable name.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Which type can hold a text value or null?