assignment_as_condition
Reports an assignment of a bool used as a whole condition, such as if (done = true). Compare with ==, or assign on a line of its own.
- Tier
- blocking
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- none
What it reports
Section titled “What it reports”A condition that is an assignment of a bool with =, where == was most likely meant: if (done = true). It is reported when the assignment is the whole condition, in any number of parentheses, of:
- an
ifor afor, as a statement or as a collection element; - a
whileor adoloop; - a conditional expression;
- an
assert.
It does not report:
- an assignment inside a comparison,
while ((line = reader.readLine()) != null): the assignment is meant, and the comparison tests its result; - an assignment that is one operand of the condition,
ready && (done = check()); - a compound assignment,
if (cached ??= compute()); - the
caseof anif, which is a pattern, not an assignment.
An assignment through a setter that does more than store the value is reported as well.
if (done = true) sets done and takes the branch every time. while (more = next()) stores the result in more and tests it. The first is always a mistake; the second can be meant, but reads as one. Either way, the condition does not test what the variable held before, which == would.
In Dart only a bool can stand there, so the mistake compiles exactly where it matters.
The rule is blocking because the branch is taken whatever the state was.
Example
Section titled “Example”void finish(Task task) { if (task.done = true) { archive(task); }}void finish(Task task) { if (task.done) { archive(task); }}Where the assignment is meant, write it on a line of its own:
var more = next();while (more) { more = next();}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. |
assay: rules: assignment_as_condition: exclude: ["lib/generated/**"]Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// The flag keeps the answer for the next round and is the condition.// ignore: assay/assignment_as_condition// ignore_for_file: assay/assignment_as_condition silences it in a whole file, and // ignore: assignment_as_condition without the prefix works too. See Suppressions.