Sub topic 9
Why Fields Do Not Always Promote, and How to Work Around It
This chapter assumes you know T versus T?, the null-aware operators, and how a null check promotes a local variable. Here you learn why the same check often fails on a field, which fields promote in current Dart, and which workaround to choose when one does not. The private final field rule needs Dart 3.2 or later.
The symptom
A null check on a local variable promotes it. The same check on a field often does not:
class Box {
String? value;
int length() {
if (value == null) return 0;
// return value.length; // Error: 'value' can't be accessed because it is nullable
return 0;
}
}
void main() {
print(Box().length()); // 0
}The check value == null is right there, and the compiler still treats value as String? on the next line. The compiler is not missing something obvious. It cannot prove that the second read of value returns the same thing as the first.
Why the compiler refuses
Flow analysis tracks what is known about a variable between two points in the code. For a local variable, the compiler can see every assignment, so it knows whether anything changed in between. A field is different, for these reasons:
- Other code can assign it. A field that is not
finalcan be reassigned by any code that holds the object. Calls between the check and the use may change it. - A read can run code. In Dart, a field read through a public name looks the same as a getter call. A subclass can override the field with a getter that returns a different value each time.
- Overrides may live in other libraries. The compiler checks one library at a time. It cannot see a subclass written elsewhere, so a public name must be assumed overridable.
- The value may be computed. A getter can return
nullon one call and a string on the next.
Promotion is only sound if two reads of the same expression give the same value. A mutable or overridable field cannot guarantee that, so the compiler declines.
The table lists what promotes under current Dart, assuming the null check comes first.
| Declaration | Promotes? | Reason |
|---|---|---|
| Local variable (not reassigned after the check) | Yes | All assignments are visible |
| Parameter | Yes | Same as a local variable |
| `final String? _x` field, private | Yes (Dart 3.2+) | Cannot be reassigned, cannot be overridden from another library |
| `final String? x` field, public | No | A subclass in another library could override it with a getter |
| `String? _x` field, private, not final | No | Can be reassigned between the check and the use |
| Getter, such as `String? get x` | No | May compute a different result each call |
| Top-level variable that is not final | No | Any code can assign it |
The Dart 3.2 rule: private final fields promote
Starting with Dart 3.2, a field promotes when two conditions hold. The field is final, so it never changes after construction. The field is private (its name starts with _), so only code in the same library can see it and the compiler can check every override.
class Profile {
final String? _bio;
Profile(this._bio);
int bioLength() {
if (_bio == null) return 0;
return _bio.length; // _bio is promoted to String here
}
String describe() {
final bio = _bio;
return bio == null ? 'No bio' : 'Bio: $bio';
}
}
void main() {
print(Profile('Hello').bioLength()); // 5
print(Profile(null).bioLength()); // 0
print(Profile(null).describe()); // No bio
}For this to compile, the package must declare a language version of at least 3.2 in pubspec.yaml:
environment:
sdk: ^3.2.0A same-name declaration can still block it
Promotion of a private name depends on every declaration with that name in the whole library, not only on the field you are looking at. If the library contains another class with a non-final field or a getter named _bio, the compiler assumes an object might be an instance of that class, and _bio is no longer promotable anywhere in the library.
class A {
final String? _bio;
A(this._bio);
int length() {
if (_bio == null) return 0;
// return _bio.length; // Error if another class in this library has a getter named _bio
return _bio?.length ?? 0;
}
}
class B {
String? get _bio => DateTime.now().second.isEven ? 'x' : null;
}
void main() {
print(A('abc').length()); // 3
print(B()._bio == null || true); // true
}The fix is to rename one of the two members, or to use a local copy as described below. This is an edge case, but it explains reports of "promotion works in one file but not after I added a class".
Workarounds
When the field cannot promote, pick the lightest workaround that fits. The diagram shows the order I recommend.
1. Copy the field to a local variable
This works on every Dart 3 version and for every kind of field, getter, or top-level variable. You read the field once, so there is nothing to change between the check and the use:
class Counter {
int? limit;
int count = 0;
bool atLimit() {
final l = limit; // one read; l cannot change
if (l == null) return false;
return count >= l; // l is promoted to int
}
}
void main() {
final c = Counter()..count = 5;
print(c.atLimit()); // false
c.limit = 5;
print(c.atLimit()); // true
}Use final for the local variable. A final local cannot be reassigned, so promotion cannot be lost later in the method.
2. Bind with a null-check pattern
The Dart 3 pattern case final v? does the copy and the check in one step, and the bound name is non-nullable inside the branch:
class Settings {
String? theme;
String banner() {
if (theme case final t?) {
return 'Theme: ${t.toUpperCase()}';
}
return 'Default theme';
}
}
void main() {
final s = Settings();
print(s.banner()); // Default theme
s.theme = 'dark';
print(s.banner()); // Theme: DARK
}3. Use null-aware operators when you only need one access
If the field is used once, you do not need promotion at all. ?. and ?? read the field exactly once, so they are always safe:
class Contact {
String? email;
String domain() => email?.split('@').last ?? 'unknown';
}
void main() {
final c = Contact();
print(c.domain()); // unknown
c.email = '[email protected]';
print(c.domain()); // example.com
}4. Redesign the field
If you control the class, the best fix is often to change the declaration rather than the use. A value set once in the constructor should be final. Making it private and exposing it through a method or a non-nullable getter often removes the nullable type from the public API completely.
class Account {
final String? _nickname;
Account({String? nickname}) : _nickname = nickname;
String get displayName {
if (_nickname == null) return 'Anonymous';
return _nickname; // promoted: private and final
}
}
void main() {
print(Account().displayName); // Anonymous
print(Account(nickname: 'Ace').displayName); // Ace
}Callers see String displayName, so they never handle null.
5. The `!` operator as a last resort
value! throws a runtime error if the value is null. It silences the compiler without proving anything, so the guarantee of sound null safety no longer covers that line. Use it only when the program's logic makes null impossible and a local copy would add noise. If you do use it, check once and keep the check close:
class Session {
String? token;
String requireToken() {
final t = token;
if (t == null) throw StateError('Not signed in');
return t; // clear failure message, no bare !
}
}
void main() {
final s = Session();
try {
s.requireToken();
} on StateError catch (e) {
print(e.message); // Not signed in
}
}An explicit throw with a message gives a clearer failure than the generic error from !.
Common mistakes
- Writing
if (obj.field != null) obj.field!.use(). This reads the field twice and still needs!. A local copy avoids both. - Assuming
finalalone is enough. A publicfinalfield still does not promote, because the name can be overridden in another library. Privacy is the second condition. - Forgetting the language version. Private final promotion does nothing on an SDK constraint below 3.2.
- Making a field
lateto avoid the null check.latechanges when initialization happens. It does not give the compiler a promotion guarantee, and reading it too early throws at runtime. - Reassigning the local copy. If you write
v = other;after the check, the compiler may demotevback to nullable. Keep the copyfinal.
Summary of decisions
- Declaring the field yourself and it never changes: make it
finaland private. - Field is public, mutable, or a getter: copy it to a
finallocal, or use a null-check pattern. - One use only:
?.or??. - The value truly cannot be null and you want to assert it: throw a descriptive error rather than relying on
!.
Exercise
This class compiles on Dart 3.2 or later without an error. Remove one word and add one word and the line return _label.length; no longer compiles. What change breaks it, and how would you fix the code without changing the field's declaration?
class Tag {
final String? label;
Tag(this.label);
int size() {
if (label == null) return 0;
return label.length;
}
}
Show answer
Removing final (making the field a plain mutable String? _label) breaks promotion, because a mutable field can change between the check and the use. Making the name public (label) breaks it for the same reason: a subclass in another library could override it. Without changing the declaration, copy it into a local variable: final label = _label; if (label == null) return 0; return label.length;. A pattern also works: if (_label case final l?) return l.length; return 0;.