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 != nullorvalue == null
What it reports
Section titled “What it reports”An if statement or if element whose case clause only tests for null:
if (value case != null);if (value case _?), alsofinal _?;if (value case == null)andif (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, andcase const (null); - a case with a
whenclause; - 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.
Example
Section titled “Example”int lengthOf(String? name) { if (name case != null) return name.length; return 0;}int lengthOf(String? name) { if (name != null) return name.length; return 0;}Rule parameters
Section titled “Rule parameters”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. |
Suppressing it
Section titled “Suppressing it”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.