Skip to content

loop_exits_on_first_pass

Reports a loop whose body leaves it on every pass. Put the leaving statement under the condition it was meant for, or replace the loop with an if.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
none

A loop whose body leaves it on every pass: a statement on the body’s own level, not under a condition, is a break, a return, a throw, a rethrow or a continue of an outer loop, and nothing before it starts the next pass. The loop runs its body once at most, yet reads as if it ran it for each element. The violation is on the leaving statement.

It does not report:

  • a loop with a continue of its own before the leaving statement, which lets it go on;
  • a do loop, a while (true) or a for (;;) loop, which are written to be left from inside;
  • a for loop with an update, which the analyzer already reports as dead code at the update;
  • a for-in loop that takes its first element on purpose: it leaves by a break or a return, no statement of its body before that is an if or a switch, and the body uses the loop’s variable, as for (final item in items) return item.name; does.

The common shape is a search whose “not found” return slipped into the loop: for (final user in users) { if (user.id == id) return user; return null; } looks at the first user only. The loop runs, the tests with one element pass, and the second element is never seen.

Violating
bool anyExpired(List<Token> tokens) {
for (final token in tokens) {
if (token.isExpired) return true;
return false;
}
return false;
}
Corrected
bool anyExpired(List<Token> tokens) {
for (final token in tokens) {
if (token.isExpired) return true;
}
return false;
}

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.

Write why on the line directly above the suppression, which goes above the line of the leaving statement:

// Only the newest entry matters; the list is sorted by time.
// ignore: loop_exits_on_first_pass
return entry;

// ignore_for_file: assay/loop_exits_on_first_pass silences it in a whole file, and // ignore: assay/loop_exits_on_first_pass with the prefix works too. See Suppressions.