Skip to content

loop_over_known_empty

Reports a for-in loop over a list or set that an if has just found empty. Fix the test, or loop over the collection you meant.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

A loop like if (items.isEmpty) { for (final item in items) … }, which never runs. It is reported when:

  • the if tests emptiness itself:
    • for its first branch: isEmpty, length == 0 or !isNotEmpty, alone or as an operand of &&;
    • for its else: isNotEmpty, length != 0, length > 0 or !isEmpty, alone;
  • the condition calls nothing and reads no getter written in the source;
  • the collection is a local variable, a parameter or a final field, read the same way in the test and the loop, and its type is a core List or Set;
  • the loop is a statement of the branch itself, and every statement before it only declares variables with values that run no code.

A call, an assignment or any other statement before the loop could fill the collection, so the loop is then not reported.

The branch was meant for the other case, or the loop for another collection. Either way the code in the loop is dead, and what it was written to do never happens.

Violating
void showErrors(List<String> errors) {
if (errors.isEmpty) {
for (final error in errors) {
log(error);
}
}
}
Corrected
void showErrors(List<String> errors) {
if (errors.isNotEmpty) {
for (final error in errors) {
log(error);
}
}
}

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:

// The loop stays for the day the list is filled before it.
// ignore: loop_over_known_empty
for (final item in items) {

// ignore_for_file: assay/loop_over_known_empty silences it in a whole file, and the prefixed // ignore: assay/loop_over_known_empty works too. See Suppressions.