Sub topic 2
Null checks and type promotion
This chapter assumes you know Dart classes, constructors, and nullable types such as String?. You should also be able to run code with dart run or DartPad.
Null checks and type promotion
When you check a nullable local variable against null, the compiler narrows its type. This is called type promotion. Inside the branch where the value is not null, Dart treats the variable as its non-nullable type.
void printLength(String? s) {
if (s == null) return;
print(s.length); // s is promoted to String here
}Promotion does not work for mutable fields. Another part of the program could change the field between the check and the use. Copy the field into a local variable first.
class Box {
String? value;
int length() {
final v = value;
if (v == null) return 0;
return v.length;
}
}The ! operator: when to use it and when not to
The null assertion operator ! tells the compiler to treat a nullable value as non-nullable. If the value is null at runtime, the program throws an error. Use ! only when you know the value is not null and the compiler cannot see that.
void main() {
String? token = 'abc';
print(token!.length); // 3
}| Situation | Better choice |
|---|---|
| You need to branch on the value | `if (x != null)` |
| You have a fallback value | `x ?? fallback` |
| You know more than the compiler does | `x!`, with a comment explaining why |
Initializing fields: required parameters and initializer lists
A non-nullable field must have a value before the constructor finishes. You can pass it as a required named parameter, or compute it in an initializer list after the colon.
class User {
final String name;
final String? email;
final int id;
User({required this.name, this.email}) : id = name.length;
}
void main() {
final user = User(name: 'Ada');
print(user.email ?? 'no email'); // no email
print(user.id); // 3
}late and late final: deferred and lazy initialization
late tells Dart that a variable will be set before its first read. The compiler does not check this. Reading an unset late variable throws at runtime. A late final field with an initializer runs that code on first read and caches the result.
class Report {
late final String text = _build();
String _build() {
print('building');
return 'report';
}
}
void main() {
final r = Report();
print('created');
print(r.text); // building, then report
print(r.text); // report
}Exercise
Why does Box.length copy value into a local variable before the null check?
Show answer
A mutable field can change between the check and the use, so the compiler cannot promote it. A local variable cannot change in that gap, so the check promotes it to String.