Skip to content

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

A literal that fixes a condition or a part of it:

  • A true or false beside a value in && or ||. It either decides the operation (ready && false is always false, ready || true always true), or does nothing (true && ready and ready || false are ready).
  • A switch statement or expression on a literal, switch (1), which takes the same case every time.

It does not report:

  • false && value and true || value: their right operand never runs, and the analyzer reports it as dead code;
  • an operation whose every operand is a literal, true && false or (1 == 1) || false, which literal_only_boolean_expressions reports;
  • a constant that is no literal, kDebugMode && verbose or switch (mode): its value is set elsewhere, and depending on it is the point;
  • a switch on 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.

Violating
bool canEdit(User user) => user.isOwner || true;
String label(bool compact) => (true && compact) ? 'S' : 'Small';
Corrected
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.

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/**"]

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.