
The ! Operator Is a Promise, Not a Fix: Sound Null Safety in Dart
- كاتب موثّق
- Dart 3
محتويات المقال
Null check operator used on a null value, thrown from the account screen. It hits only people who signed up with a phone number, because their email is null. Three months earlier, the analyzer had flagged profile.email as possibly null, the IDE offered a quick fix, and one keystroke made the red underline disappear. That keystroke was a !.
The common misconception
! and late are harmless ways to quiet the analyzer. You know the value won't be null, the analyzer is being pedantic, and a single character settles the argument.
error is never read when it's null, a relationship the type checker can't follow. IDEs offer "add a null check" as a one-click fix. And developers who come from TypeScript or C# carry over the rule that a postfix ! changes nothing at runtime, which is exactly what those languages' docs say about their versions of it. In Dart, it does.
What actually happens
Sound null safety is a guarantee, not a lint
String can't hold null, and String? can. With , enforced since Dart 3, the promise is strong: if an expression's static type doesn't permit null, no execution of it can ever produce null. The analyzer errors you see are how Dart keeps that promise before your code runs, and Dart's docs credit the design with fewer bugs, smaller binaries and faster execution.
! is a cast that's checked at runtime
! is a cast that's checked at runtime! always throws if the value is null. It doesn't fix the null. It converts a compile-time error into a possible runtime exception, on that line.
class Profile { Profile({this.email}); final String? email; // null until the user verifies it}String greeting(Profile profile) { // The analyzer is quiet now. The runtime isn't. return 'Signed in as ${profile.email!}';}void main() { print(greeting(Profile(email: 'sara@example.com'))); print(greeting(Profile())); // Null check operator used on a null value}class Profile { Profile({this.email}); final String? email; // null until the user verifies it}String greeting(Profile profile) { final email = profile.email; // a local copy, so the null check promotes it if (email == null) return 'Signed in (email not verified)'; return 'Signed in as $email';}void main() { print(greeting(Profile(email: 'sara@example.com'))); print(greeting(Profile())); // Signed in (email not verified)}dart run and it prints Signed in as sara@example.com, then stops with an unhandled exception: Null check operator used on a null value, pointing at the line with !. The second prints both greetings.
Why the analyzer pushed you toward !
!if (profile.email != null) and the analyzer still complained, because works on local variables, parameters and, since Dart 3.2, private final fields. email is a public field, and the analyzer says so: "'email' refers to a public property so it couldn't be promoted." Another library could override it with a getter that returns something different the second time. Copying it into a local, as in the right version, gives the analyzer a value that can't change between the check and the use.
late is a promise about timing
late is a promise about timinglate makes the same deal for initialization. In Dart's words, it means "enforce this variable's constraints at runtime instead of at compile time". Each read checks that the variable was assigned, and throws a LateInitializationError if it wasn't. A late final also checks that it's assigned only once. In Flutter, the classic mistake is a field that's filled by an async call:
class _ProfilePageState extends State<ProfilePage> { late User _user; // a promise: assigned before build() reads it @override void initState() { super.initState(); loadUser().then((user) => setState(() => _user = user)); } @override Widget build(BuildContext context) => Text(_user.name); // frame 1: throws}class _ProfilePageState extends State<ProfilePage> { User? _user; // null means "not loaded yet", and the type says so @override void initState() { super.initState(); loadUser().then((user) { if (mounted) setState(() => _user = user); }); } @override Widget build(BuildContext context) { final user = _user; // a local copy, so the null check promotes it if (user == null) return const CircularProgressIndicator(); return Text(user.name); }}build() runs right after initState, long before the future completes. In a widget test, the first frame of the wrong version threw LateInitializationError for _user; the right version showed a spinner, then the name.
String? plus if (x == null) … | ||
x ?? 'fallback', x?.length | null flows on | |
x! | x is null | |
late String x; | ||
late final String x; |
How to apply it in your project
Audit the `!` and `late` you already have Search the codebase for both. For each one, ask: what guarantees this value is there? If the answer is "it usually is", make the type nullable and handle the null. Copy fields into locals before checking them final email = profile.email;then checkemail. Promotion works on the local, the check and the use see the same value, and the!disappears.Model "not yet" and "missing" in the type Data that loads asynchronously, optional server fields and unverified user input are nullable by nature. Use ?, a loading state or a default with??instead oflate.Make the analyzer's quick fix your last option When the IDE offers "add a null check", read it as "add a runtime crash if I'm wrong". Try promotion, ??or?.first.
Key takeaways
Dart's null safety is sound: a non-nullable type can never hold null at runtime, so the compiler checks your promises. !is a cast checked at runtime; it throwsNull check operator used on a null valueif the value is null.latemoves initialization checks to runtime and throwsLateInitializationErroron a read before assignment.Promote with a local variable and a null check, or use ??and?., before reaching for!.Keep !andlatefor invariants you can prove, not for values that are merely usually there.
التعليقات (0)