Skip to main content

avoid-non-null-assertion

added in: 1.6.0
βš™οΈ
Free+

Warns when the non-null assertion operator (! or β€œbang” operator) is used on a property access or method invocation.

This operator check works at runtime and it may fail and throw a runtime exception. The rule ignores the index [] operator on the Map class because it's considered the idiomatic way to access a known-present element in a map with []! according to the docs.

note

Use this rule if you want to avoid possible unexpected runtime exceptions.

βš™οΈ Config​

Set skip-checked-fields (default is false) to allow non-null assertions on fields that are checked to be non-null in an if statement (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-non-null-assertion:
skip-checked-fields: false

Example​

❌ Bad:

class Test {
String? field;

Test? object;

void method() {
field!.contains('other'); // LINT: Avoid non-null assertions. Try rewriting the code without it.

object!.field!.contains('other'); // LINT: Avoid non-null assertions. Try rewriting the code without it.

object!.method(); // LINT: Avoid non-null assertions. Try rewriting the code without it.

if (object case int!) { // LINT: Avoid non-null assertions. Try rewriting the code without it.
// ...
}
}
}

βœ… Good:

class Test {
String? field;

Test? object;

void method() {
field?.contains('other');

object?.field?.contains('other');

final map = {'key': 'value'};
map['key']!.contains('other');

object?.method();
}
}

Example with "skip-checked-fields"​

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-non-null-assertion:
skip-checked-fields: true

βœ… Good:

class Test {
String? field;

void method() {
if (field != null) {
field!.contains('other'); // Correct, checked for non-null before
}
}
}

Additional Resources​