Sub topic 12
Writing Extensions on Nullable Types
Assume you know Dart variables, functions, classes, constructors, static types, and null-aware operators. This chapter focuses on adding reusable behavior to values whose type may be null.
An extension adds methods or getters to an existing type without changing that type or creating a subclass. An extension on String? can be called when the receiver is either a String or null. This makes it useful for common checks and conversions at application boundaries.
Declaring an extension on a nullable type
The type after on is the receiver type. To support null, write String?, not String.
extension NullableStringX on String? {
bool get isNullOrEmpty {
final value = this;
return value == null || value.isEmpty;
}
String orDefault(String fallback) {
final value = this;
return value ?? fallback;
}
}
void main() {
String? missing;
String? present = 'Dart';
print(missing.isNullOrEmpty); // true
print(present.isNullOrEmpty); // false
print(missing.orDefault('Unknown')); // Unknown
print(present.orDefault('Unknown')); // Dart
}Inside the extension, this has type String?. Copying it to the local variable value lets flow analysis promote it after the null check. The expression value == null || value.isEmpty is safe because the right side runs only when value is not null.
The same extension is available on a non-nullable String. A String value can be used where String? is expected, so both of these calls are valid:
print(''.isNullOrEmpty);
print('hello'.orDefault('fallback'));Why use a nullable extension?
Without an extension, callers repeat the same conditional logic:
String displayName(String? name) {
if (name == null || name.trim().isEmpty) {
return 'Anonymous';
}
return name.trim();
}An extension centralizes that rule:
extension DisplayNameX on String? {
String displayName() {
final value = this?.trim();
return value == null || value.isEmpty ? 'Anonymous' : value;
}
}
void main() {
String? name = ' Ada ';
print(name.displayName()); // Ada
}Use an extension when the behavior is a small, general operation on the receiver. Use a separate service or function when the operation needs application state, I/O, configuration, or a complex business rule.
| Choice | Suitable when |
|---|---|
| Extension on `T?` | The operation safely handles both a value and `null` |
| Extension on `T` | Calling with `null` should be impossible |
| Separate function or class | The operation needs dependencies or substantial business logic |
Null handling inside an extension
Null-aware operators remain available inside the extension. The ?. operator stops an operation and returns null when the receiver is null. The ?? operator supplies a fallback.
extension NullableStringFormatX on String? {
String get quoted => this == null ? '(missing)' : '"$this"';
int get lengthOrZero => this?.length ?? 0;
}
void main() {
String? value;
print(value.quoted); // (missing)
print(value.lengthOrZero); // 0
}Be careful with !. It tells the compiler that a nullable value is non-null, but it throws a runtime exception if that promise is false. Prefer a null check, ?., or ?? when the null case is valid.
An extension does not add storage, constructors, or fields to the original class. It also cannot override an existing member. If the original type already has a member with the same name, that member takes precedence over the extension.
Exercise
Why does an extension declared with on String fail to provide a method for a String? receiver, and how would you change it to support both?
Show answer
String excludes null, so declare the extension with on String?. The extension can then handle the null branch with ?., ??, or an explicit null check.