Skip to content

constant_index_in_indexed_loop

Reports a constant index, such as items[0], in an indexed for loop over that collection. Index with the loop variable.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

An integer literal as the index into the collection that an indexed for loop counts through: for (var i = 0; i < items.length; i++) use(items[0]);. Every pass reads the same element.

The loop is judged when:

  • it declares one variable, and its condition bounds it by the length of a collection that is a chain of names: i < items.length, i <= items.length - 1, or the same the other way round;
  • its body does not mention the loop’s variable at all;
  • its body mentions the collection only to index it or to read its length. A body that calls a method of the collection, such as removeAt(0) in a loop that drains it, or hands it on, is not judged.

The loop was meant to visit every element, and visits the first one as many times as there are elements.

A queue drained in a while loop, queue[0] then removeAt(0), is a different shape and is never reported.

Violating
var total = 0;
for (var i = 0; i < prices.length; i++) {
total += prices[0];
}
Corrected
var total = 0;
for (var i = 0; i < prices.length; i++) {
total += prices[i];
}

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 repeats the first frame as many times as there are frames.
// ignore: assay/constant_index_in_indexed_loop

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