Sub topic 13
Null safety in legacy and mixed code
This chapter assumes you know the earlier chapters on T versus T?, null-aware operators, and promotion. It covers what happens when you meet code written before null safety. It also covers the places where null can still reach a null-safe program.
The situation under Dart 3
Null safety arrived in Dart 2.12 as an opt-in feature. For several releases, one program could mix null-safe and legacy libraries. Dart 3 ended that period. It supports only sound null safety, and every library must be null safe.
For you today, the relevant facts are:
- Dart 3 does not compile code that opts out of null safety.
- The
--no-sound-null-safetyflag no longer exists. - The
dart migratetool is not part of Dart 3. - A package can no longer use a legacy dependency, because no legacy dependencies are accepted.
"Mixed code" therefore means two things now. The first is a codebase you are moving from the pre-2.12 style to Dart 3. The second is a null-safe program that still receives untyped data from JSON, platform channels, or dynamic APIs.
How the old mixed mode worked
You can recognize legacy code in the wild by a few markers. Knowing them helps when you read old tutorials, Stack Overflow answers, and package histories.
| Feature | Legacy (before 2.12) | Dart 3 |
|---|---|---|
| Opt-in mechanism | SDK constraint lower bound of 2.12 or higher, or a `// @dart=2.9` comment to opt out | Always on |
| Type of `String` | Could hold `null` (internally `String*`) | Never holds `null` |
| Soundness | Unsound when mixed with legacy libraries | Sound |
| Typical `pubspec.yaml` SDK line | `sdk: ">=2.7.0 <3.0.0"` | `sdk: ^3.0.0` or newer |
| Missing value | Any variable could be `null` | Only `T?` can be `null` |
In mixed mode, a null-safe library calling a legacy one could not trust the types it received. A legacy function declared as returning String might return null, and a null-safe caller would crash later, far from the cause. The compiler tried to limit the damage, but the guarantee was weaker. This is why sound null safety was only complete once the whole program was migrated.
Recognizing legacy code
You will usually see it in one of three forms.
- A
pubspec.yamlwhose SDK constraint has a lower bound under 2.12 or an upper bound of<3.0.0. - A file that starts with a language version comment such as
// @dart=2.9. - Code that uses
nullas the normal state of any variable, with checks likeif (name == null)on parameters typedString.
Here is a pubspec fragment from a typical legacy package:
environment:
sdk: ">=2.7.0 <3.0.0"Dart 3 reports that no version of the SDK satisfies this constraint, so dart pub get fails. The <3.0.0 upper bound alone is enough to cause the failure, even if the code inside happens to be fine. The updated form is:
environment:
sdk: ^3.0.0Changing the constraint does not migrate the code. It only declares that the package now targets Dart 3, and the analyzer will then report every place where the code still assumes the old rules.
A migration workflow
The overall path depends on how much code you have and whether your dependencies are already updated.
The order matters. Dependencies come first, because your code cannot compile against a library that does not support Dart 3. Within your own package, work from the files with the fewest imports toward the files that import many others. The nullability of a low-level function's parameters determines what its callers must do.
If you maintain a large package that has not been migrated at all, there is one more option. You can install an older SDK from the 2.19 line, where dart migrate still exists, run the tool, and then move to Dart 3 afterwards. This is a one-time route, and you still review the result by hand.
Making the decision for each declaration
Migration is not a mechanical rewrite. For each variable, parameter, field, and return type, you decide whether null is a meaningful value. Consider this legacy function, which is written in the pre-2.12 style:
// @dart=2.9
String describe(String name, int age) {
if (name == null) return 'unknown';
return age == null ? name : '$name ($age)';
}The code checks both parameters for null, so the original author expected callers to pass null. The right migration keeps that behavior and makes it visible in the types:
String describe(String? name, int? age) {
if (name == null) return 'unknown';
return age == null ? name : '$name ($age)';
}
void main() {
print(describe(null, null)); // unknown
print(describe('Ada', null)); // Ada
print(describe('Ada', 36)); // Ada (36)
}If instead no caller ever passed null, you would declare String name and int age and delete the checks. Removing the checks is the better change, because dead branches hide bugs. The analyzer helps here. With a non-nullable parameter, a leftover name == null check produces a warning that the condition is always false.
Common patterns you will meet
- Optional parameters. In legacy code, an optional positional parameter without a default silently defaulted to
null. In Dart 3, either give it a default value or make its type nullable. - Fields set in
initState-style methods. Legacy classes often declared fields that were assigned after construction. Uselateif the value is always set before first use, orT?if it can genuinely be missing. - Returning
nullas "not found". Make the return typeT?and let callers use??or a null check. Listwith null holes.new List(5)created a list full ofnull. UseList<int?>.filled(5, null), or build the list with real values.
On that last point, the old List constructor was removed, and the replacements make the intent explicit:
void main() {
final slots = List<int?>.filled(3, null);
slots[1] = 7;
print(slots); // [null, 7, null]
final zeros = List<int>.filled(3, 0);
print(zeros); // [0, 0, 0]
}Null can still enter a null-safe program
Sound null safety guarantees that a value of type String is not null when the program is type correct. That guarantee holds only if the value really has that type. Several boundaries let untyped data in, and the compiler cannot check them:
dynamicvalues, such as the result ofjsonDecode.- Platform channels and plugin return values in Flutter apps.
- Foreign function calls through
dart:ffior JavaScript interop. - Anything you cast with
as.
At these points a wrong assumption fails loudly, because a cast like as String throws when the value is null. That is better than the old behavior, where a null could travel through many calls before it caused a crash. It still means you should validate data at the boundary and convert it to proper typed objects once.
import 'dart:convert';
class Profile {
final String name;
final String? email;
final int age;
Profile({required this.name, this.email, required this.age});
factory Profile.fromJson(Map<String, dynamic> json) {
final name = json['name'];
if (name is! String) {
throw FormatException('name must be a string, got $name');
}
final age = json['age'];
return Profile(
name: name,
email: json['email'] as String?,
age: age is int ? age : 0,
);
}
}
void main() {
final data = jsonDecode('{"name": "Ada", "age": 36}') as Map<String, dynamic>;
final profile = Profile.fromJson(data);
print(profile.email ?? 'no email'); // no email
try {
Profile.fromJson({'age': 1});
} on FormatException catch (e) {
print(e.message); // name must be a string, got null
}
}The constructor treats each field according to its meaning. name is required, so a missing or wrongly typed value is an error. email is optional, so as String? accepts either a string or null, but still throws if the JSON holds a number. age falls back to a default. After fromJson returns, the rest of the program works with Profile and never needs to ask whether name is null.
A rule for boundaries
Parse once, at the edge, and let the types carry the result inward. If you find as String or ! scattered through the middle of your code, the boundary is too far from the data source.
Gotchas when updating old code
- Old tutorials. Examples written before 2023 may use
// @dart=2.9,new List(), or unannotated nullable fields. They will not compile as written. - Generated code. Files produced by older code generators may carry a language version comment or legacy patterns. Regenerate them with current versions of the generator packages rather than editing by hand.
- Test code. Tests are libraries too and must be null safe. Mock return values often need
T?or explicit stubs where the old code returnednullimplicitly. - Dependency overrides. A
dependency_overridesentry can force a legacy package into resolution, but Dart 3 will still refuse to compile it. Replace the package instead. - Public APIs. If you publish a package, changing a parameter from
TtoT?is compatible for callers, but changing a return type fromTtoT?breaks them. Plan your nullability decisions with your version number in mind.
Checking your work
After the analyzer is clean, the migration is not finished. Run the tests, and then search the codebase for the risky constructs:
- Count the uses of
!and justify each one. - Look for
ascasts ondynamicvalues and confirm each sits at a boundary. - Check each
latefield for a code path that reads it before assignment. - Search for
?? ''and?? 0defaults that hide missing data you should report.
Exercise
A legacy package has sdk: ">=2.10.0 <3.0.0" in its pubspec, and one function int parse(String s) that returns null when the input is not a number. List the changes needed for Dart 3, including the new signature of parse.
Show answer
Raise the SDK constraint to a Dart 3 range such as ^3.0.0, because the <3.0.0 upper bound makes dart pub get fail. Then change the return type to int?, since null is a meaningful result meaning "not a number". The body can be return int.tryParse(s);. Callers then handle the result with ??, a null check, or a pattern, rather than assuming a value.
Exercise
Why does final age = json['age'] as int; fail at runtime when the JSON has no age key, and how would you handle an optional age?
Show answer
json['age'] returns null for a missing key, and null is not an int, so the cast throws a TypeError. For an optional age, cast to the nullable type with as int? and store it in an int? field, or use a default such as (json['age'] as int?) ?? 0 if a default is acceptable.