Sub topic 12
Writing Extensions on Nullable Types
Prerequisites
This chapter assumes you know the following:
- How
TandT?differ. - How
?.and??work. - How flow analysis promotes local variables.
- How to declare a basic Dart extension (
extension Name on Type { ... }).
Why extend a nullable type
Without help, every call on a nullable value needs a guard. A check like s == null || s.isEmpty appears in form validation, JSON handling and UI code. You can write the guard each time, or you can give it a name once.
An extension declared on a nullable type lets you do that. The members you add can be called on a value of type String? without a ?. or ! at the call site. Inside the extension, the receiver may be null, and your code decides what that means.
This works because an instance method call on null fails at runtime, but an extension member is not an instance method. Dart picks the extension at compile time from the static type of the receiver, and the call is compiled as an ordinary static function call that receives the value as this. A null this is legal when the extension is declared on a nullable type.
A first extension
extension NullableStringX on String? {
bool get isNullOrEmpty => this == null || this!.isEmpty;
}
void main() {
String? a;
print(a.isNullOrEmpty); // true
print(''.isNullOrEmpty); // true
print('x'.isNullOrEmpty); // false
}Three points about this code:
- The extension is declared
on String?, so the getter is available onString?values such asa. - It is also available on plain
Stringvalues such as'', becauseStringis a subtype ofString?. - The reverse is not true. An extension declared
on Stringcannot be called on aString?, and the compiler reports an error. That error is the point of null safety: it forces the caller to decide what to do about null.
Writing the body: `this` does not promote
Inside an extension, this is the receiver. Flow analysis does not promote this after a null check. That is why the first example writes this!.isEmpty. The ! there is safe, because this == null || has already handled the null case. It still looks like the unchecked assertion the earlier chapter warned about.
A cleaner pattern copies this into a local variable. Locals promote normally.
extension NullableStringX on String? {
bool get isNullOrEmpty {
final self = this;
return self == null || self.isEmpty;
}
String orDefault(String fallback) {
final self = this;
return self == null || self.isEmpty ? fallback : self;
}
int? get asIntOrNull {
final self = this;
return self == null ? null : int.tryParse(self);
}
}
void main() {
String? input;
print(input.orDefault('anonymous')); // anonymous
print('42'.asIntOrNull); // 42
print(input.asIntOrNull); // null
}This is the same local-variable workaround you use for mutable fields. It keeps the body free of !, so a later edit is less likely to introduce a real null error.
Pitfall: `?.` skips the extension
Null-aware access short-circuits when the receiver is null. If you write ?. in front of an extension member, Dart never calls the extension for a null receiver.
extension NullableStringX on String? {
bool get isNullOrEmpty {
final self = this;
return self == null || self.isEmpty;
}
}
void main() {
String? a;
print(a.isNullOrEmpty); // true
print(a?.isNullOrEmpty); // null
}The second line has type bool? and evaluates to null. The extension body never runs, and the null case you wrote the extension for is silently skipped. Call extension members on nullable receivers with a plain .. The Dart analyzer may flag an unnecessary ?. when the extension's receiver type is nullable, but do not rely on that.
Generic extensions on `T?` and collections
You can make an extension generic when the same idea applies to many types. A common case is an Iterable<T>? that you want to treat as empty when it is null.
extension NullableIterableX<T> on Iterable<T>? {
bool get isNullOrEmpty {
final self = this;
return self == null || self.isEmpty;
}
Iterable<T> get orEmpty => this ?? Iterable<T>.empty();
}
void main() {
List<int>? scores;
print(scores.isNullOrEmpty); // true
for (final s in scores.orEmpty) {
print(s); // never runs
}
scores = [3, 4];
print(scores.orEmpty.length); // 2
}Because List<int> is a subtype of Iterable<int>, the extension applies to lists, sets and any other iterable. The type parameter T is inferred from the receiver.
Mind the difference between Iterable<T>? and Iterable<T?>. The first is a collection that may be missing. The second is a collection that may contain null elements. To strip nulls from the second kind, the core library has the nonNulls getter, available since Dart 3.0. Check the SDK before you write your own version of something that common.
An extension on a bare T? applies to every type, which makes it easy to cause name clashes:
extension OrX<T> on T? {
T or(T fallback) => this ?? fallback;
}
void main() {
int? count;
print(count.or(0)); // 0
print('hi'.or('x')); // hi
}This is short, but the ?? fallback operator already does the same thing. An extension earns its place when it names a domain concept or bundles several steps. It does not earn its place by renaming one operator.
Resolution rules and gotchas
Extension members follow a few rules that matter more once the receiver can be null.
- Instance members win. If the receiver's type already has a member with the same name, the instance member is chosen and the extension is ignored.
Object?hastoString,hashCode,==andruntimeType. These work on null already, so you cannot override them through an extension. - Resolution is static. The compiler uses the declared type of the expression. A value typed
dynamicnever uses extensions, sodynamic d = null; d.isNullOrEmptyfails at runtime withNoSuchMethodError. - Conflicts are errors. If two imported extensions both apply and neither is more specific, the call is ambiguous. Resolve it with
show,hide, an import prefix, or by calling the extension explicitly asNullableStringX(a).isNullOrEmpty. - More specific wins. An extension on
Stringtakes priority over one onString?when the receiver is a non-nullString, so you can offer different behavior for the two cases. - Unnamed extensions are private.
extension on String? { ... }is visible only in its own library. Name an extension if other files need it.
The table summarizes where an extension is callable.
| Extension declared on | Call on `String` | Call on `String?` |
|---|---|---|
| `String` | Yes | No, compile-time error |
| `String?` | Yes | Yes |
| `Object?` | Yes | Yes |
Design guidance
Before you add an extension on a nullable type, check these points.
- Does it return something useful for null?
isNullOrEmpty,orEmptyandasIntOrNullall have an obvious answer for null. If the honest result of a method on null is "this is a bug", leave the receiver non-nullable and make callers handle null. - Is the name honest?
isNullOrEmptytells the reader that null is expected. A name such aslength2hides that fact. - Is it scoped narrowly? Prefer
String?orIterable<T>?overObject?. A broad extension appears in autocomplete for every value in the project. - Does it promote anything? An extension getter cannot promote the caller's variable. After
if (!s.isNullOrEmpty), the variablesis stillString?, and the caller still needs a!or a separate null check. If promotion at the call site matters, use an explicits != nullcheck or a pattern.
extension NullableStringX on String? {
bool get isNullOrEmpty {
final self = this;
return self == null || self.isEmpty;
}
}
void shout(String? s) {
if (!s.isNullOrEmpty) {
// print(s.toUpperCase()); // Error: s is still String?
print(s!.toUpperCase()); // Works, but needs the assertion
}
if (s != null && s.isNotEmpty) {
print(s.toUpperCase()); // Promoted, no assertion
}
}
void main() {
shout('dart'); // DART twice
}The last point is the main limit of this technique. The getter reads well, but the compiler cannot see through it. Use extensions to make code short and clear where promotion is not needed, and use plain null checks where it is.
Exercise
Write an extension named NullableMapX<K, V> on Map<K, V>? with a getter isNullOrEmpty that returns true when the map is null or has no entries. Write it without using !. Then say what m.isNullOrEmpty returns for Map<String, int>? m = null.
Show answer
extension NullableMapX<K, V> on Map<K, V>? {
bool get isNullOrEmpty {
final self = this;
return self == null || self.isEmpty;
}
}
The local variable self is promoted to Map<K, V> after the self == null check fails, so self.isEmpty needs no assertion. For Map<String, int>? m = null, m.isNullOrEmpty returns true, because the extension is called with this set to null and the first condition is true.
Exercise
Given extension NullableStringX on String? { bool get isNullOrEmpty => this == null || this!.isEmpty; } and String? s = null;, what do s.isNullOrEmpty and s?.isNullOrEmpty evaluate to? Explain the difference, and say why if (!s.isNullOrEmpty) print(s.length); does not compile.
Show answer
s.isNullOrEmpty evaluates to true. The extension is called with this set to null. s?.isNullOrEmpty evaluates to null with type bool?, because the null-aware access skips the call when the receiver is null, so the extension body never runs. The if example does not compile because an extension getter does not promote the caller's variable. After the check, s still has type String?, so s.length is an error. Use s!.length or an explicit s != null check instead.