Working with Nullable Values
Prerequisites: Null safety
Dart gives you several tools for nullable values.
Null-aware access: ?.
void main() {
String? nickname;
String? city = 'Oslo';
print(nickname?.length);
print(city?.length);
print(city?.toUpperCase());
}
null
4
OSLO
?. returns null instead of failing when the value is null.
Default values: ?? and ??=
void main() {
String? saved;
final name = saved ?? 'Guest';
print(name);
final quantity = int.tryParse('abc') ?? 1;
print(quantity);
String? theme;
theme ??= 'light';
print(theme);
}
Guest
1
light
a ?? b—aif it isn'tnull, otherwiseb.x ??= value— assigns only ifxis currentlynull.
Type promotion
After you check that a local variable isn't null, Dart treats it as
non-nullable automatically:
void describe(String? input) {
if (input == null) {
print('Nothing entered');
return;
}
print('You typed ${input.length} characters');
}
void main() {
describe('hello');
describe(null);
}
You typed 5 characters
Nothing entered
This is called type promotion. The early return for the missing
case — a guard clause — keeps the main code simple.
The ! operator (use sparingly)
! asserts that a value isn't null. If it is, the program throws:
void main() {
String? value;
print(value!.length);
}
Unhandled exception:
Null check operator used on a null value
Treat ! as a warning sign — there's almost always a safer option.
late
late declares a non-nullable variable that will be assigned before it's
used, but not right away:
late final String description;
void main() {
description = 'Set once, later';
print(description);
}
Set once, later
Reading a late variable before it's assigned throws a
LateInitializationError.
Practice
Write int parseAge(String text) that returns the number in text, or
0 if it isn't valid. Call it with '36' and 'abc'.
Show solution
int parseAge(String text) => int.tryParse(text) ?? 0;
void main() {
print(parseAge('36'));
print(parseAge('abc'));
}
36
0