Sub topic 5
Null checks and type promotion
This chapter assumes you can read Dart code that uses String and String?, and that you know what ?. and ?? do. It also assumes you can run a file with dart run or in DartPad. The goal is to explain how the compiler decides that a nullable variable is safe to use, and what breaks that decision.
What promotion is
A variable declared as String? has the type String? everywhere in its scope. The compiler tracks more than that. It follows every path through your code and records what it has learned about the variable at each point. If the code has proven the value is not null, the compiler treats the variable as String at that point. This is called type promotion. The tracking mechanism is called flow analysis.
int lengthOrZero(String? s) {
if (s == null) return 0;
return s.length;
}
void main() {
print(lengthOrZero('Ada')); // 3
print(lengthOrZero(null)); // 0
}The declared type of s never changes. Inside the rest of the function, the compiler knows s cannot be null, so s.length is allowed. Without the check, the same expression is a compile-time error: "The property 'length' can't be unconditionally accessed because the receiver can be 'null'."
How the compiler reasons
Flow analysis follows branches and joins. At a join point, such as the end of an if statement, the compiler keeps only the facts that are true on every incoming path.
In the example above, the then branch ends with return, so control never flows from it to the code after the if. The only path that reaches return s.length is the one where s != null, so the promotion holds there.
Checks that promote
Many kinds of test promote a variable. They differ in where the promotion applies.
| Condition | Promoted to non-null | Column | Column | Column | Column |
|---|---|---|---|---|---|
| `if (x != null) A else B` | In `A` | ||||
| `if (x == null) A else B` | In `B` | ||||
| `if (x == null) { exit }` then more code | After the `if` | ||||
| `x != null && use(x)` | On the right of `&&` | ||||
| `x == null \ | \ | use(x)` | On the right of `\ | \ | ` |
| `x != null ? a : b` | In `a` | ||||
| `x is T` | In the true branch, as type `T` |
The boolean operators work like short-circuit evaluation. The right side of && only runs when the left side was true, and the right side of || only runs when the left side was false. The compiler uses that fact.
bool isBlank(String? s) => s == null || s.trim().isEmpty;
bool startsWithA(String? s) => s != null && s.startsWith('A');
int safeLength(String? s) => s != null ? s.length : 0;
void main() {
print(isBlank(null)); // true
print(isBlank(' ')); // true
print(startsWithA('Ada')); // true
print(safeLength(null)); // 0
}Reversing the operands breaks promotion. s.isEmpty || s == null fails to compile, because s.isEmpty runs before any check.
Early exits
The most common pattern is a guard that leaves the current flow. Anything that stops control from reaching the next statement counts: return, throw, break, continue, and a call to a function whose return type is Never.
Never fail(String message) => throw ArgumentError(message);
String describe(String? s) {
if (s == null) fail('s is required');
return s.toUpperCase();
}
void main() {
print(describe('abc')); // ABC
}A call that returns Never is known never to return normally, so the code after it is reachable only when s is not null.
Inside loops, continue is a convenient guard:
void main() {
final inputs = <String?>['a', null, 'ccc'];
var total = 0;
for (final item in inputs) {
if (item == null) continue;
total += item.length;
}
print(total); // 4
}The guard style keeps the main path of a function at one level of indentation. It is usually easier to read than wrapping everything in if (x != null) { ... }.
Promotion with `is`
Promotion is not only about null. It works for any type test, which is useful when a value has a broad type such as Object?.
String describe(Object? value) {
if (value is int) return 'int ${value + 1}';
if (value is String) return 'string ${value.length}';
if (value == null) return 'null';
return 'other: $value';
}
void main() {
print(describe(41)); // int 42
print(describe('Ada')); // string 3
print(describe(null)); // null
print(describe(2.5)); // other: 2.5
}is T promotes to T. The negative form is! T promotes on the other branch, so if (value is! String) return; leaves value as a String afterwards.
Assignments change what the compiler knows
Assigning to a variable replaces what flow analysis knew about it. Assigning a non-null value promotes the variable. Assigning a nullable value demotes it, which means the compiler goes back to the declared type.
String? lookup(int id) => id == 1 ? 'Ada' : null;
void main() {
String? name = 'Ada';
print(name.length); // 3, the initializer promoted name
name = lookup(2); // the result is String?, so name is demoted
print(name?.length); // null
if (name == null) {
name = 'guest';
}
print(name.length); // 5
}The last print compiles because both paths into it leave name non-null. On the path where the if ran, the assignment promoted it. On the path where the if was skipped, the condition name == null was false.
Loops need care. If a loop body assigns a nullable value to a variable you checked before the loop, the compiler must assume the check no longer holds on the next iteration. It demotes the variable at the top of the loop.
Where promotion applies
Promotion only works when the compiler can be sure that nothing changes the variable between the check and the use. These variables qualify:
- Local variables.
- Function parameters.
- Variables captured by a closure, as long as nothing reassigns them after the closure is created or inside it.
Instance fields, top-level variables and getters usually do not promote. Any other code, including other threads of control such as callbacks, could change them between your check and your use. A later chapter covers the fields case and the local-variable workaround.
For closures, final locals are the easiest case, because they cannot be reassigned.
String? readToken() => 'abc';
void main() {
final token = readToken();
void Function() show = () {};
if (token != null) {
show = () => print(token.length); // token is still promoted here
}
show(); // 3
}If token were a var that something reassigns later, the compiler would not trust the check inside the closure. The closure might run after the reassignment.
What does not promote
Some code looks like a null check but gives the compiler nothing to use.
x?.lengthreturnsint?and does not change the type ofx.- A check on a different expression. After
if (a.name != null), the compiler promotes nothing abouta.nameifnameis a field. Afterif (list.isNotEmpty), it learns nothing about nullability. - A check inside a helper function. If
isPresent(x)returns abool, the caller learns nothing, because promotion cannot see inside the function body. - A condition that is not about the variable itself, such as
if (s?.isNotEmpty ?? false). Rewrite this asif (s != null && s.isNotEmpty).
bool isPresent(String? s) => s != null;
void main() {
String? s = DateTime.now().year > 2000 ? 'x' : null;
if (isPresent(s)) {
// print(s.length); // Error: s is still String? here
print(s?.length);
}
if (s != null && s.isNotEmpty) {
print(s.length); // fine
}
}Common errors and fixes
| Message or symptom | Likely cause | Fix |
|---|---|---|
| "The property 'length' can't be unconditionally accessed because the receiver can be 'null'." | No check before the access | Add a guard, or use `?.` |
| "A value of type 'String?' can't be assigned to a variable of type 'String'." | The value is nullable and the compiler cannot prove otherwise | Check first, or give a default with `??` |
| Promotion works, then stops | A nullable value was assigned in between | Check again after the assignment, or store the result in a new `final` variable |
| Check on a field has no effect | Fields do not promote | Copy the field to a local variable first |
| Warning about an unnecessary null comparison | The variable is already non-nullable | Remove the check |
The last row matters because the check is harmless at runtime but misleading. If the analyzer says s == null is always false, the declared type already excludes null. Either the check is dead code, or the type should be nullable.
Choosing between promotion and the operators
Use promotion when you need the non-null value more than once, or when you need to do something different in the null case. Use ?. and ?? when a single expression is enough.
String shout(String? s) {
if (s == null) return 'nothing';
final trimmed = s.trim();
return trimmed.isEmpty ? 'blank' : trimmed.toUpperCase();
}
String shortVersion(String? s) => s?.trim().toUpperCase() ?? 'nothing';
void main() {
print(shout(' hi ')); // HI
print(shortVersion(null)); // nothing
}The two functions differ slightly: shout reports blank for whitespace, and shortVersion returns an empty string. The first is longer but easier to extend with more cases.
Exercises
Exercise
This function does not compile. Explain why, and fix it without using the ! operator.
String? find(String key) => key == 'a' ? 'apple' : null;
String firstLetter(String key) {
final value = find(key);
return value[0];
}
Show answer
find returns String?, so value has type String? and value[0] is an unsafe index on a possibly null value. No check precedes it, so there is no promotion. Add a guard: if (value == null) return ''; before return value[0];. Alternatively, use value?[0] ?? '' if you want a single expression.
Exercise
In the following code, does the final line compile? Explain what flow analysis knows at that point. void main() { String? s = 'x'; s = DateTime.now().year > 2000 ? null : 'y'; print(s.length); }
Show answer
It does not compile. The initializer promotes s to String, but the second assignment has type String?, so flow analysis demotes s back to String?. The compiler cannot know which branch of the conditional ran. Add a null check before the print, or use s?.length.
Exercise
Why does if (s.isEmpty || s == null) fail to compile when s is a String? parameter, and what is the correct order?
Show answer
|| evaluates its left side first, and s.isEmpty runs before any null check, so the access is unsafe. The correct order is s == null || s.isEmpty. Now the right side only runs when s == null is false, and the compiler promotes s to String there.