Sub topic 13
Null safety in legacy and mixed code
This chapter assumes basic Dart syntax, classes, constructors, static types, and running Dart programs. It focuses on code that is being migrated from pre-null-safety Dart or that calls an older library.
Why legacy code needs care
Dart's sound null safety requires every value to have a clear nullability contract. A String must contain a string, while a String? may contain null.
Older Dart code was written before this distinction existed. A function that used to return String might return null at runtime even though its declaration does not show that possibility. When null-safe code calls such an API, the boundary is treated cautiously. The value may be considered potentially nullable until your code checks it.
Dart 3 requires sound null safety for the program as a whole. You cannot keep running an entirely non-null-safe application by disabling null safety. Migration therefore includes the application, its packages, generated code, and any API boundaries between old and new code.
A migration boundary
The safest approach is to isolate uncertain values in a small adapter. The adapter receives a value from the old boundary, validates it, and returns a precise null-safe type.
The following program uses legacyReadName as a stand-in for an older library function:
String? legacyReadName() {
// An old API could return null even when its documentation was unclear.
return null;
}
String readName() {
final raw = legacyReadName();
if (raw == null || raw.trim().isEmpty) {
return 'Unknown';
}
return raw.trim();
}
void main() {
print(readName());
}After the check, raw is promoted from String? to String within the remaining branch. The rest of the application can call readName without repeating the legacy API's uncertainty.
Migration choices and common errors
| Situation | Safer choice | Common error |
|---|---|---|
| Old API can return no value | Return `T?` and check it | Declare `T` and trust the old behavior |
| A missing value has a valid default | Use `??` | Use `!` and risk a crash |
| Input must exist for an operation | Validate at the boundary | Pass nullable data through many layers |
| A package is not null safe | Upgrade or migrate it | Hide errors with `dynamic` |
| A value is checked once | Copy it to a local variable | Assume a mutable field stays non-null |
A migration can expose errors in three important places:
- Declarations: Fields, parameters, and return types need explicit nullability.
- Initialization: Non-nullable fields must be initialized before a constructor finishes.
- External data: JSON, databases, preferences, and platform APIs can contain missing or malformed values even when their Dart types look safe.
Use Object? when an input truly can contain any value. Convert it deliberately:
String displayName(Object? value) {
if (value is String && value.trim().isNotEmpty) {
return value.trim();
}
return 'Unknown';
}
void main() {
print(displayName('Ada'));
print(displayName(null));
print(displayName(42));
}dynamic removes many static checks, so it should stay at a narrow boundary. Validate the value, then expose a typed result to the rest of the program.
A practical migration sequence
- Update dependencies and generated sources that support null safety.
- Read analyzer errors as missing contracts, not merely syntax problems.
- Decide whether each value is required, optional, or replaceable by a default.
- Change public APIs first, then fix their callers.
- Add tests for absent fields, empty strings, malformed data, and missing records.
- Remove temporary
dynamicvalues and unnecessary!assertions.
Exercise
Why is an adapter better than adding ! at every call site of a legacy API?
Show answer
An adapter checks the uncertain value once, gives the rest of the application a clear type contract, and avoids repeated runtime assertion failures.