compare_to_for_equality
Reports a.compareTo(b) == 0 on strings and integers. Write a == b.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- writes
==or!=
What it reports
Section titled “What it reports”a.compareTo(b) == 0 or != 0, with the zero on either side, where a and b are both a String, both an int or both a BigInt.
Not judged:
doubleandnum: NaN and -0.0 makecompareToand==disagree;DateTime: its==also compares the time zone;Durationand every other class: a subclass may givecompareToor==its own meaning;- an
intcompared with anum, and?.compareTo.
The fix writes == or !=, with brackets around a compared value that binds less tightly than ==.
For these types compareTo gives zero exactly when == holds, so the comparison is an equality test written the long way.
Example
Section titled “Example”Violating
bool same(String a, String b) => a.compareTo(b) == 0;Corrected
bool same(String a, String b) => a == b;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:
// The ordering is what this check is about; it reads as the sort below it.// ignore: assay/compare_to_for_equality// ignore_for_file: assay/compare_to_for_equality silences it in a whole file, and // ignore: compare_to_for_equality without the prefix works too. See Suppressions.