Sub topic 4
Sound null safety
This chapter assumes you understand Dart variables, control flow, and functions. It also assumes basic object-oriented programming. Dart’s sound null safety makes the type system track whether a value can be null, so code can avoid many null-reference errors before it runs.
Nullable and non-nullable types
A non-nullable type cannot contain null:
String name = 'Ada';
int count = 3;A nullable type adds ? to the type name:
String? nickname;
int? score = null;Dart requires you to check a nullable value before using it as a non-nullable value. This rule is checked statically, by the analyzer.
String uppercase(String? value) {
if (value == null) {
return 'UNKNOWN';
}
return value.toUpperCase();
}After the if check, Dart promotes value from String? to String inside the remaining branch. This flow analysis also works with early returns.
Operators for nullable values
Dart provides operators for common null-handling decisions.
| Operator | Purpose | Example |
|---|---|---|
| `?.` | Call or access only when non-null | `user?.name` |
| `??` | Use a fallback when null | `name ?? 'guest'` |
| `??=` | Assign only when currently null | `name ??= 'guest'` |
| `!` | Assert that a value is non-null | `name!` |
String? findUser(int id) => id == 1 ? 'Ada' : null;
void main() {
final user = findUser(2);
print(user?.toUpperCase() ?? 'UNKNOWN');
String? nickname;
nickname ??= 'guest';
print(nickname);
}The ?. operator returns null instead of calling a member when user is null. The ?? operator then supplies a fallback. The ??= operator changes nickname only if it has no value.
The non-null assertion operator, !, changes a nullable expression into a non-nullable one:
String? token = 'abc';
print(token!.length);This is safe only when you know token cannot be null at that point. Otherwise, ! throws an exception at runtime. Prefer a check or a fallback when either is clear.
Nullable fields and parameters
A nullable field must be initialized or declared with a nullable type. Constructors often use required for values that must be supplied:
class Profile {
final String name;
final String? bio;
Profile({required this.name, this.bio});
String summary() => bio?.trim() ?? 'No biography';
}
void main() {
final profile = Profile(name: 'Ada');
print(profile.summary());
}The bio field may be null, so summary handles that case explicitly. The name field is non-nullable because the constructor requires it.
Common errors
- Assigning
nullto a non-nullable variable: useString?if absence is valid. - Calling a method directly on a nullable value: check it or use
?.. - Confusing
!with a null check:!makes an assertion; it does not test the value. - Forgetting that
Map[key]can return null when the key is missing, even when the map’s values are non-nullable.
Exercise
What does user?.toUpperCase() ?? 'UNKNOWN' produce when user is null?
Show answer
?. produces null without calling toUpperCase, and ?? replaces that null with UNKNOWN.