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
What it reports
Section titled “What it reports”A loop like if (items.isEmpty) { for (final item in items) … }, which never runs. It is reported when:
- the
iftests emptiness itself:- for its first branch:
isEmpty,length == 0or!isNotEmpty, alone or as an operand of&&; - for its
else:isNotEmpty,length != 0,length > 0or!isEmpty, alone;
- for its first branch:
- 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
ListorSet; - 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.
Example
Section titled “Example”void showErrors(List<String> errors) { if (errors.isEmpty) { for (final error in errors) { log(error); } }}void showErrors(List<String> errors) { if (errors.isNotEmpty) { for (final error in errors) { log(error); } }}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. |
Suppressing it
Section titled “Suppressing it”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_emptyfor (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.