الانتقال إلى المحتوى
تطبيقات الموبايلDart· 7 دقائق للقراءة

The ! Operator Is a Promise, Not a Fix: Sound Null Safety in Dart

! and late don't remove a null: they move Dart's check from compile time to a runtime exception on that line.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Dart 3
محتويات المقال

The top crash in this week's report is a single line: 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

The belief: ! 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.

It's an understandable habit. The analyzer sometimes really can't see what you can: Dart's own guide shows a response class where 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

In Dart, types are non-nullable by default: 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.

So when you write something the compiler can't prove, Dart doesn't simply take your word for it. To keep the guarantee sound, it inserts a check that runs every time.

! is a cast that's checked at runtime

The takes the expression on its left and casts it to the underlying non-nullable type. Dart's guide is direct: the cast must be checked at runtime, and ! 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.

Dart greeting.dart
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}

Run the first version with 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 !

Often the developer did check. They wrote 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 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:

Dart profile_page.dart
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}

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.

What you writeChecked at compile timeWhat happens at runtime
String? plus if (x == null) …Every use, after promotionNothing can throw on null
x ?? 'fallback', x?.lengthThe null case is handledThe default or null flows on
x!Nothing: you promisedThrows if x is null
late String x;Nothing about assignmentThrows if read before it's assigned
late final String x;Nothing about assignmentAlso throws on a second assignment

How to apply it in your project

  1. Audit the `!` and `late` you already haveSearch 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.
  2. Copy fields into locals before checking themfinal email = profile.email; then check email. Promotion works on the local, the check and the use see the same value, and the ! disappears.
  3. Model "not yet" and "missing" in the typeData that loads asynchronously, optional server fields and unverified user input are nullable by nature. Use ?, a loading state or a default with ?? instead of late.
  4. Make the analyzer's quick fix your last optionWhen 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 throws Null check operator used on a null value if the value is null.
  • late moves initialization checks to runtime and throws LateInitializationError on a read before assignment.
  • Promote with a local variable and a null check, or use ?? and ?., before reaching for !.
  • Keep ! and late for invariants you can prove, not for values that are merely usually there.

📚 المصادر

  1. Sound null safety — Dart
  2. Understanding null safety — Dart
  3. Variables — Dart
  4. Fixing type promotion failures — Dart

التعليقات (0)