Sub topic 3
Why fields do not always promote, and how to work around it
This chapter assumes you know Dart classes, nullable types (T?), and null checks. You should also be able to run code with dart run or DartPad.
Flow analysis promotes a nullable local variable after a null check, so the compiler treats it as non-nullable. Fields do not always get this treatment. A mutable field can change between the check and the use, so the compiler refuses to promote it.
class Box {
String? value;
int length() {
final v = value; // copy to a local variable so it can be promoted
if (v == null) return 0;
return v.length;
}
}Copying the field into a local final variable is the standard fix.
flowchart TD
A["Field value has type String?"] --> B["if (field == null) return"]
B --> C["Using field directly: still String?, not promoted"]
A --> D["final v = field"]
D --> E["if (v == null) return"]
E --> F["v is promoted to String"]caption: Copying a mutable field into a local variable lets the compiler promote it. alt: A flowchart showing that checking a field directly leaves it nullable, while copying it to a local variable first allows promotion to a non-nullable type.
Nullable elements and Map lookups
List<int?> is a list whose elements may be null. List<int>? is a list that may itself be null. A Map lookup returns a nullable value when the key is missing, so use ?? to supply a default.
void main() {
final ages = <String, int>{'ann': 30};
final age = ages['bob']; // type is int?
print(age ?? -1); // -1
List<int?> withGaps = [1, null, 3];
List<int>? maybeList;
print(withGaps.length); // 3
print(maybeList?.length); // null
}Null-check patterns with Dart 3
Dart 3 lets you match a nullable value with case final n?. The pattern matches only non-null values and binds them to a non-nullable variable.
void greet(String? name) {
if (name case final n?) {
print('Hello, $n');
} else {
print('Hello, stranger');
}
}Extensions on nullable types
An extension declared on String? can be called on a null receiver, so it can handle the null case itself.
extension NullableStringX on String? {
bool get isNullOrEmpty => this == null || this!.isEmpty;
}Null safety in legacy and mixed code
Dart 3 requires null safety. Older code written before null safety must be migrated, or it will not compile against the current language. Mixed code, where migrated and unmigrated libraries call each other, needs care at the boundary. Check the types that legacy APIs return, and add null checks where a value might be null.
::: callout note Use ! only when you can prove the value is non-null. A failed ! throws at runtime, which removes the compile-time protection that null safety provides. :::
Exercise
In the Box example, why does the code copy value into v before the null check?
Show answer
The field is mutable, so the compiler does not promote it after the check. The local final variable v cannot change, so the compiler promotes it to String.