constant_condition
Reports a true or false literal that fixes an && or ||, and a switch on a literal. Remove the literal, or test what you mean.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- delete a literal that does nothing
What it reports
Section titled “What it reports”A literal that fixes a condition or a part of it:
- A
trueorfalsebeside a value in&&or||. It either decides the operation (ready && falseis always false,ready || truealways true), or does nothing (true && readyandready || falseareready). - A
switchstatement or expression on a literal,switch (1), which takes the same case every time.
It does not report:
false && valueandtrue || value: their right operand never runs, and the analyzer reports it as dead code;- an operation whose every operand is a literal,
true && falseor(1 == 1) || false, whichliteral_only_boolean_expressionsreports; - a constant that is no literal,
kDebugMode && verboseorswitch (mode): its value is set elsewhere, and depending on it is the point; - a
switchon a record or a collection,switch ((a, b)), which matches two values at once.
A literal in a condition is usually a value someone typed in while trying something, if (isAdmin || true) to see the admin screen, and that stayed. The condition no longer depends on what it names, and the reader has to find out which half counts. A switch on a literal is the same: one case runs, the others are dead.
The rule is advisory because the code runs as written; it only does not say what it does.
Example
Section titled “Example”bool canEdit(User user) => user.isOwner || true;
String label(bool compact) => (true && compact) ? 'S' : 'Small';bool canEdit(User user) => user.isOwner;
String label(bool compact) => compact ? 'S' : 'Small';The fix deletes a literal that does nothing, with its operator: true && ready and ready && true become ready, and so do false || ready and ready || false. The other operand is kept as written, parentheses and all, and runs as before.
There is no fix where the literal decides the operation, ready && false or ready || true, nor for a switch on a literal: which part was meant cannot be told from the code.
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: constant_condition: exclude: ["lib/generated/**"]Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// The check stays off until the service answers; the flag returns then.// ignore: assay/constant_condition// ignore_for_file: assay/constant_condition silences it in a whole file, and // ignore: constant_condition without the prefix works too. See Suppressions.