avoid-non-null-assertion
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
}
}
}