Skip to content

avoid_non_null_assertion

Reports a ! null assertion that no null test guards. Handle the null case instead.

Tier
blocking
Scope
Dart
Fix
none

Every ! null assertion that no null test of the same expression guards:

  • a postfix operator: value!, value!.length, list![0], callback!(), lookup(key)!. In a!.b! each ! is its own violation.
  • a null-assert pattern: case final value!, final (left!, right) = pair, whatever stands before it.

It does not report:

  • a guarded assertion, while allow_guarded is true (the default). Dart does not promote a property tested for null, so after if (widget.onTap != null) you still write widget.onTap!. See Guarded assertions;
  • logical negation !flag, the operator !=, and the negated type test value is! String;
  • the null-aware operators ?., ?? and ??=, and the null-check pattern case final value?;
  • the ! after a lookup that incomplete_enum_map_lookup reports, where that rule judges the file.

! tells the compiler that a value is not null without checking it. When the claim is wrong, the program throws at run time, at a place that names neither the value nor why it was expected, and a null-assert pattern throws the same way. The null case is still there: it has only moved from the compiler’s report to the user’s device.

Violating
String initial(Map<String, String> names, String id) {
final name = names[id]!;
return name.substring(0, 1);
}
Correctedby deciding what a missing entry means
String initial(Map<String, String> names, String id) {
final name = names[id];
if (name == null || name.isEmpty) {
return '?';
}
return name.substring(0, 1);
}

Other ways to handle the null case, depending on what null means there:

  • give a default: names[id] ?? 'unknown';
  • pass the null on: names[id]?.substring(0, 1);
  • match only the non-null case: if (names[id] case final name?) { … };
  • fail on purpose, with an error that says what was expected: throw StateError('No name for $id').

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
allow_guarded true Allows a guarded assertion. false reports it like any other.
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.
assay:
rules:
avoid_non_null_assertion:
allow_guarded: false
exclude: ["lib/interop/**"]

Write why on the line directly above the suppression:

// Every enum value gets a label in the constructor, so the entry exists.
// ignore: assay/avoid_non_null_assertion

// ignore_for_file: assay/avoid_non_null_assertion silences it in a whole file, and // ignore: avoid_non_null_assertion without the prefix works too. See Suppressions.

All cases

The ! after a lookup that incomplete_enum_map_lookup reports (_labels[status]! in a map keyed by an enum that leaves a constant out) is left to that rule where it judges the file: it says why the ! throws. Where it does not (core does not switch it on), this rule reports the !. A ! inside the key, _labels[holder!.status]!, is still this rule’s.

Dart promotes a local variable that was tested for null, but not a property: after if (widget.onTap != null), widget.onTap is still nullable, and you must write widget.onTap! all the same. That ! is a guarded assertion, and by default the rule does not report it. These three are guarded:

if (result.user == null) {
throw UserNotFoundException();
}
return result.user!;
if (metadata.title != null) _titleController.text = metadata.title!;
final actions = [
if (widget.onAddToListPressed != null)
MenuAction(onPressed: widget.onAddToListPressed!),
];

The rule decides from the syntax alone, and where there are two readings it takes the one that reports.

E! is guarded when all three of these hold:

  1. E is a chain of names: an identifier or a property access with ., such as title, metadata.title, this.metadata.title, widget.onTap, Settings.instance. A leading this. and parentheses make no difference: this.title and (title) are the same expression as title, as long as both mean the same declaration, not a field in one place and a local variable in the other. A call find()!, a lookup map[key]!, and a chain with a ?. or another ! in it are no chains. In a.b!.c! the first ! can be guarded and the second cannot.

  2. A null test of E leads to the assertion. null != E and null == E count like E != null and E == null. The assertion stands in:

    • the then-part of if (E != null): of an if statement, of a collection if, or of an if-case whose when clause is the test. The test may be one operand of a chain of &&: if (ready && E != null);
    • the else-part of if (E == null). The test may be one operand of a chain of ||;
    • the code after an earlier if (E == null) that has no else-part and always leaves, in the same block or in a block around it within the same function. It always leaves when it is a return, a throw, a rethrow, a continue or a break, or a block that ends in one;
    • the right operand of E != null && … or of E == null || …;
    • the then-branch of E != null ? … : …, or the else-branch of E == null ? … : …;
    • the body of while (E != null).

    An assert(E != null) is no guard: asserts do not run in a release build.

  3. Nothing between the test and the assertion breaks the guard, in the order of the source:

    • Neither E nor a part of its chain is assigned. metadata.title = null, metadata = other, metadata.title ??= '' and metadata++ all break a guard on metadata.title, and so do a cascade, a pattern assignment or a for (metadata in …) that assigns one of them. An assignment whose value holds the assertion breaks nothing: node = node.next!.
    • The function is not suspended: no await, await for or yield, since other code may run while it waits. An await before the test breaks nothing, and neither does one whose operand holds the assertion: await send(metadata.title!).
    • The assertion is not in a function declared after the test, such as a closure, a local function or the initializer of a late variable: that code runs later. A test inside the same closure guards as anywhere else.

    In a loop that begins after the test, an assignment or an await anywhere in the loop breaks the guard, even below the assertion: from the second round on, it comes first.

These are no guards, so the assertion after them is reported:

  • a loop other than while: the body and the last part of for (; E != null; …), and the body of do … while (E != null), which runs once before the test;
  • a test in another form: !(E == null), E is T, the when clause of a switch case, and a?.b != null as a test of a;
  • an earlier if that has an else-part, or that leaves by a call of a function that returns Never, such as fail(); an earlier if among the statements of a switch case that are not in a block of their own;
  • an await or an assignment that stands between the test and the assertion in the source, also one in a branch that returns before the assertion.

A guarded ! can still throw (see the caution above). assay accepts this on purpose. Testing a property and then asserting it is how Dart is written where promotion is not possible, and a gate that fails on code whose author did test for null teaches people to suppress the rule, not to handle null.

The form that needs no assertion reads the property once, so nothing can change between the test and the use, and the compiler checks it:

if (metadata.title case final title?) _titleController.text = title;
final user = result.user;
if (user == null) {
throw UserNotFoundException();
}
return user;

To have every assertion reported, guarded or not, set allow_guarded to false.