Sub topic 4
Sound null safety
This chapter assumes you know the Dart basics from the earlier chapters: var, final, const, functions with named parameters, and classes with fields. You should also know that many languages let any reference be null. Dart does not.
Why null safety exists
In many languages, calling a method on null crashes the program at runtime. Dart moves that check to compile time. In Dart 3, every type is non-nullable by default. A String always holds a string. If a value may be absent, you write String?.
The guarantee is called sound. If the analyzer accepts your code, a non-nullable variable can never hold null at runtime. The compiler can also use this guarantee to generate faster code. Dart 3 supports only sound null safety, so you cannot turn it off.
void main() {
String name = 'Ada';
String? nickname; // implicitly null
print(name.length); // 3
print(nickname); // null
// name = null; // compile-time error
// print(nickname.length); // compile-time error
}The two commented lines do not compile. The second one is rejected because nickname might be null, so .length is not safe to call.
The type hierarchy
T is a subtype of T?. A String can go anywhere a String? is expected, but the reverse is not allowed. The type Null has one value, null, and it is a subtype of every nullable type.
Object does not include null either. Use Object? for "anything, including null". dynamic also allows null, but it turns off most static checks, so prefer Object?.
The null-aware operators
| Operator | Meaning | Example |
|---|---|---|
| `?` after a type | The type allows `null` | `int? age` |
| `?.` | Call only if the receiver is not null, otherwise the result is `null` | `user?.length` |
| `?[]` | Index only if the receiver is not null | `list?[0]` |
| `??` | Use the right side if the left side is `null` | `a ?? 'x'` |
| `??=` | Assign only if the variable is currently `null` | `a ??= 'x'` |
| `!` | Assert the value is not null | `a!` |
String? findUser(int id) => id == 1 ? 'Ada' : null;
void main() {
final user = findUser(2);
print(user?.toUpperCase() ?? 'unknown'); // unknown
String? nickname;
nickname ??= 'guest';
print(nickname); // guest
}?. short-circuits the whole chain. In a?.b.c, if a is null, Dart skips both .b and .c. The result type of a ?. chain is always nullable, which is why ?? 'unknown' is needed to get back a plain String.
Type promotion
You do not have to use operators for every check. When you test a variable against null, Dart's flow analysis promotes it to the non-nullable type inside the branch where the test succeeded.
String describe(String? text) {
if (text == null) {
return 'nothing';
}
// text is promoted to String from here on
return 'length ${text.length}';
}
void main() {
print(describe(null)); // nothing
print(describe('Dart')); // length 4
}Promotion also follows &&, ||, early return, throw, and continue. After a branch that always exits, the code below sees the promoted type. This is why the early-return style above is idiomatic.
Why promotion sometimes fails
Promotion only works when the compiler can prove the value cannot change between the check and the use. These cases are not promoted:
- Instance fields that are not
final, because another method or a subclass could change them. - Getters, because they may return a different value each time.
- Local variables that are assigned in a closure after the check.
The standard fix is to copy the value into a local variable first.
class Profile {
String? bio;
int bioLength() {
// if (bio != null) return bio.length; // error: bio is not promoted
final b = bio;
if (b == null) return 0;
return b.length; // b is promoted
}
int shorter() => bio?.length ?? 0;
}
void main() {
final p = Profile();
print(p.bioLength()); // 0
p.bio = 'Dart fan';
print(p.bioLength()); // 8
print(p.shorter()); // 8
}A final field in the same library, with no getter involved, can be promoted. A mutable field never can.
Null-check patterns
Dart 3 patterns give a compact alternative. The pattern final n? matches only when the value is not null and binds it to a new, non-nullable variable.
void main() {
String? nickname = 'Ace';
if (nickname case final n?) {
print(n.length); // 3
}
}The null assertion operator
value! tells the compiler "I know this is not null". It converts T? to T. If you are wrong, the program throws an error at runtime.
void main() {
final Map<String, int> stock = {'apple': 3};
final count = stock['apple']!; // lookup returns int?, ! makes it int
print(count); // 3
final missing = stock['pear']!; // throws: Null check operator used on a null value
print(missing);
}Map lookups return V? because the key may be absent. Use ! only when you have already guaranteed the key exists. Otherwise, prefer ?? with a default, or an explicit check that handles the missing case.
Required and default parameters
Named parameters are optional by default, which means they would be null. For a non-nullable parameter you must either mark it required or give it a default.
class Config {
final String host;
final int port;
final String? label;
Config({required this.host, this.port = 80, this.label});
late final String url = 'http://$host:$port';
}
void main() {
final c = Config(host: 'example.com');
print(c.url); // http://example.com:80
print(c.label ?? 'no label'); // no label
}Here label is nullable, so it needs no default. The compiler rejects Config(port: 8080) because host is required.
Late variables
late tells Dart "I will assign this before I read it". It lets a non-nullable variable skip initialization at the declaration, and the compiler stops checking definite assignment.
late String name;is assigned later. Reading it before assignment throws aLateInitializationError.late final String url = expensive();runs the initializer lazily, on the first read, and only once.- The initializer of a
latefield may usethis, which ordinary field initializers cannot.
Use late sparingly. It moves a compile-time check to runtime, just like !. A nullable type with an explicit check is often clearer.
Nullability in collections and generics
Where the ? goes changes the meaning.
void main() {
List<String?> items = ['a', null, 'c']; // elements may be null
List<String>? maybeList; // the list itself may be null
final present = items.nonNulls.toList(); // List<String>
print(present); // [a, c]
print(maybeList?.length ?? 0); // 0
}nonNulls filters out nulls and changes the element type to the non-nullable one. The older form items.whereType<String>() does the same.
For a generic class, T can itself be nullable unless you bound it. In class Box<T>, T may be int?. Write class Box<T extends Object> to forbid nullable type arguments.
Common errors
- "The property can't be unconditionally accessed because the receiver can be null." Add
?., a null check, or a default. - Field not promoted. Copy the field into a local
finalvariable first. - Late error at runtime. A
latevariable was read before assignment. Initialize it earlier or make it nullable. - Overusing
!. It hides bugs until a user triggers them. - Confusing
List<String?>withList<String>?. Read the type from the inside out.
Exercise
The following method does not compile. Explain why, and rewrite it so it compiles without using !.
class Cart {
String? coupon;
int couponLength() {
if (coupon != null) {
return coupon.length;
}
return 0;
}
}
Show answer
coupon is a mutable instance field, so Dart cannot promote it. Another method or a subclass could set it to null between the check and the use. Copy it into a local variable: final c = coupon; if (c == null) return 0; return c.length;. A shorter version is return coupon?.length ?? 0;.
Exercise
Given Map<String, int> prices = {'tea': 3};, what are the type and value of prices['coffee'] ?? 0, and what happens with prices['coffee']!?
Show answer
The expression prices['coffee'] ?? 0 has type int and value 0, because the lookup returns int? (null for a missing key) and ?? supplies the default. prices['coffee']! compiles, but it throws a "Null check operator used on a null value" error at runtime because the key is absent.