Triagebellfor Sentry
Guide

Flutter: 'Null check operator used on a null value'

By the Triagebell team · Updated · 3 min read · How we check guides

Short answer

"Null check operator used on a null value" is the runtime error Dart throws when the postfix ! operator is applied to a value that is null. The ! told the compiler "this is never null", and at runtime it was. Find the ! on the line in the stack trace, work out why that value was null (not loaded yet, a widget no longer in the tree, a missing map key), and replace the ! with a null check, a default via ??, or code that makes the value exist first.

Steps

  1. Find the failing !Open the first stack frame from your package; the line and column point at the ! that saw null.
  2. Ask why it was nullCheck whether the value was still loading, removed from the tree, missing from a map, or reset elsewhere.
  3. Replace the !Use a null check with an early return, a local variable copy, ?? with a real default, or a loading state.
  4. Guard async gapsAfter every await in UI code, check context.mounted (or mounted in a State) before using context.
  5. Upload symbols for release buildsIf you obfuscate, upload debug symbols and the obfuscation map so the next occurrence is readable in Sentry.

What the error looks like

On iOS, Android and desktop the Dart VM throws a _TypeError with this message:

Null check operator used on a null value
#0      CartPage.build (package:acme/cart_page.dart:42:31)

When it happens inside build, Flutter reports it as The following _TypeError was thrown building CartPage(dirty): followed by the same message, and debug builds paint the red error screen. When it happens in async code nobody awaited, it appears in the log as Unhandled Exception: Null check operator used on a null value.

Two neighbours that are easy to confuse with it:

MessageCause
Null check operator used on a null valueA ! on a null value
LateInitializationError: Field 'token' has not been initialized.A late field read before it was assigned
LateInitializationError: Local 'x' has not been initialized.A late local read before it was assigned

The column number in the first stack frame points at the ! that failed, which matters when a line has several.

Causes, most common first

  1. Data not there yet. snapshot.data! in a FutureBuilder or StreamBuilder before the future completes, or user! before sign-in finished.
  2. Map lookups. json['price']! or routes[name]!: the [] operator on a Map returns null for a missing key, so one renamed API field crashes the screen.
  3. GlobalKey.currentState!. Flutter's docs say currentState is null if no widget in the tree matches the key, the widget is not a StatefulWidget, or the State is not of the expected type. _formKey.currentState!.validate() on a form that is not mounted is the classic case.
  4. Using a BuildContext after await. The widget was disposed while the request ran; a lookup that returns a nullable result, then !, fails. The use_build_context_synchronously lint flags this pattern.
  5. ! added to silence the compiler. A nullable field doesn't promote after if (field != null), so someone writes field!. Dart only promotes fields that are both private and final (since Dart 3.2); public or mutable fields can change between the check and the use.

Fixes, with code

Handle the null state in the UI instead of asserting it away:

// Before
FutureBuilder<Cart>(
  future: _cartFuture,
  builder: (context, snapshot) => Text('${snapshot.data!.items.length} items'),
);

// After
FutureBuilder<Cart>(
  future: _cartFuture,
  builder: (context, snapshot) {
    final cart = snapshot.data;
    if (cart == null) return const CircularProgressIndicator();
    return Text('${cart.items.length} items');
  },
);

Copy fields to a local before checking them; locals promote:

final user = _user;
if (user == null) return;
print(user.name); // no ! needed

Check mounted after every await before touching context, as the lint's docs show:

Future<void> _save(BuildContext context) async {
  await api.saveCart(cart);
  if (!context.mounted) return;
  Navigator.of(context).pop();
}

Inside a State, check mounted (the State's own property) rather than context.mounted. For map data, use json['price'] ?? 0 when a default is correct, or parse into a model class that throws a clear FormatException when a required field is missing.

The mistake people make next: swapping ! for ?. everywhere and returning an empty widget. The crash stops, but users see a blank screen and Sentry no longer tells you. Use ?. and ?? where null is a real state, and fail loudly with a useful message where it is not.

In Sentry: obfuscated builds need symbols

If you build with --obfuscate --split-debug-info, Sentry receives obfuscated frames and an obfuscated exception type, so the issue title is unreadable until you upload the build's debug files. Sentry's docs recommend the Sentry Dart Plugin, configured in pubspec.yaml:

sentry:
  project: web
  org: acme
  upload_debug_symbols: true
  dart_symbol_map_path: build/app/obfuscation.map.json

Build with the obfuscation map, then run the plugin with $SENTRY_AUTH_TOKEN set:

flutter build apk --obfuscate --split-debug-info=build/symbols \
  --extra-gen-snapshot-options=--save-obfuscation-map=build/app/obfuscation.map.json
dart run sentry_dart_plugin

dart_symbol_map_path needs Sentry Dart Plugin 3.2.0 or later and is what makes obfuscated Flutter issue titles readable on iOS and Android. With symbols uploaded, the first frame shows your file, line and column, which leads straight to the !. Without Sentry, flutter symbolize -i <stack-trace-file> -d <symbols-file> does the same for a single trace. Keep the symbols from every release you ship; you can't regenerate them later. More in Sentry for Flutter.

Questions

Why does Dart let me compile code that crashes with a null check error?

The ! operator is a promise to the compiler that the value is not null. Dart checks that promise at runtime and throws if it is broken.

Is this the same as LateInitializationError?

No. LateInitializationError means a late variable was read before it was assigned; the null check error means a ! met an actual null value.

Why does it only happen in release or for some users?

Usually timing: slower networks leave data null for longer, and users navigate away mid-request, so a widget is gone by the time the await returns.

Sources

  1. Understanding null safetydart.dev
  2. use_build_context_synchronouslydart.dev
  3. Obfuscate Dart codedocs.flutter.dev
  4. Sentry Dart Plugindocs.sentry.io