Skip to content

pattern_only_tests_null

Reports an if-case whose pattern only tests its value for null. Write value != null or value == null instead.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
writes value != null or value == null

An if statement or if element whose case clause only tests for null:

  • if (value case != null);
  • if (value case _?), also final _?;
  • if (value case == null) and if (value case null).

The violation covers the case clause.

It does not report:

  • a pattern that binds a name: case final bound?;
  • a pattern that also tests a type: case int _?;
  • a comparison with anything but the literal null, and case const (null);
  • a case with a when clause;
  • the cases of a switch.

The fix writes value != null or value == null, and puts a value that binds more loosely than a comparison in brackets: (first ?? second) != null. It is not offered where a comment stands between the value and the end of the pattern.

Such a pattern binds nothing and tests nothing else. The comparison says the same in the form every reader knows, and promotes a local variable or a private final field just as the pattern does.

Violating
int lengthOf(String? name) {
if (name case != null) return name.length;
return 0;
}
Corrected
int lengthOf(String? name) {
if (name != null) return name.length;
return 0;
}

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

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: pattern_only_tests_null

// ignore_for_file: assay/pattern_only_tests_null silences it in a whole file, and the prefixed // ignore: assay/pattern_only_tests_null works too. See Suppressions.