avoid_non_null_assertion
Reports a ! null assertion that no null test guards. Handle the null case instead.
- Tier
- blocking
- Scope
- Dart
- Fix
- none
What it reports
Section titled “What it reports”Every ! null assertion that no null test of the same expression guards:
- a postfix operator:
value!,value!.length,list![0],callback!(),lookup(key)!. Ina!.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_guardedistrue(the default). Dart does not promote a property tested for null, so afterif (widget.onTap != null)you still writewidget.onTap!. See Guarded assertions; - logical negation
!flag, the operator!=, and the negated type testvalue is! String; - the null-aware operators
?.,??and??=, and the null-check patterncase final value?; - the
!after a lookup thatincomplete_enum_map_lookupreports, 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.
Example
Section titled “Example”String initial(Map<String, String> names, String id) { final name = names[id]!; return name.substring(0, 1);}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').
Rule parameters
Section titled “Rule parameters”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/**"]Suppressing it
Section titled “Suppressing it”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.
Details
Section titled “Details”All cases
What it reports, in full
Section titled “What it reports, in full”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.
Guarded assertions
Section titled “Guarded assertions”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.
When exactly an assertion is guarded
Section titled “When exactly an assertion is guarded”E! is guarded when all three of these hold:
-
E is a chain of names: an identifier or a property access with
., such astitle,metadata.title,this.metadata.title,widget.onTap,Settings.instance. A leadingthis.and parentheses make no difference:this.titleand(title)are the same expression astitle, as long as both mean the same declaration, not a field in one place and a local variable in the other. A callfind()!, a lookupmap[key]!, and a chain with a?.or another!in it are no chains. Ina.b!.c!the first!can be guarded and the second cannot. -
A null test of E leads to the assertion.
null != Eandnull == Ecount likeE != nullandE == null. The assertion stands in:- the then-part of
if (E != null): of an if statement, of a collectionif, or of an if-case whosewhenclause 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 areturn, athrow, arethrow, acontinueor abreak, or a block that ends in one; - the right operand of
E != null && …or ofE == null || …; - the then-branch of
E != null ? … : …, or the else-branch ofE == null ? … : …; - the body of
while (E != null).
An
assert(E != null)is no guard: asserts do not run in a release build. - the then-part of
-
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 ??= ''andmetadata++all break a guard onmetadata.title, and so do a cascade, a pattern assignment or afor (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 fororyield, since other code may run while it waits. Anawaitbefore 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
latevariable: 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
awaitanywhere in the loop breaks the guard, even below the assertion: from the second round on, it comes first. - Neither E nor a part of its chain is assigned.
These are no guards, so the assertion after them is reported:
- a loop other than
while: the body and the last part offor (; E != null; …), and the body ofdo … while (E != null), which runs once before the test; - a test in another form:
!(E == null),E is T, thewhenclause of a switch case, anda?.b != nullas a test ofa; - an earlier
ifthat has an else-part, or that leaves by a call of a function that returnsNever, such asfail(); an earlierifamong the statements of a switch case that are not in a block of their own; - an
awaitor an assignment that stands between the test and the assertion in the source, also one in a branch that returns before the assertion.
Why guarded assertions are allowed
Section titled “Why guarded assertions are allowed”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.