Skip to main content

avoid-accessing-collections-by-constant-index

added in: 1.10.0
Pro+
preset: recommended

Warns when a collection is accessed by a constant index inside a for loop.

Accessing items by constant index inside a for loop is usually a bug. Either the index should depend on the loop, or the access should be moved outside the loop body.

Example

❌ Bad:

const _array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

void func() {
for (final element in _array) {
_array[0]; // LINT: Suspicious access to element by a constant index inside a loop. Ensure the correct index is used or move the access out of the loop.
_array[element];
_array[constIndex]; // LINT: Suspicious access to element by a constant index inside a loop. Ensure the correct index is used or move the access out of the loop.
_array[finalIndex]; // LINT: Suspicious access to element by a constant index inside a loop. Ensure the correct index is used or move the access out of the loop.
_array[mutableIndex];
_array[Some.index]; // LINT: Suspicious access to element by a constant index inside a loop. Ensure the correct index is used or move the access out of the loop.
_array[Some.mutableIndex];
}
}

class Some {
static final index = 1;
static int mutableIndex = 1;
}

const constIndex = 1;
final finalIndex = 1;
var mutableIndex = 1;

✅ Good:

const _array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

void func() {
_array[0]; // Correct, outside of the for loop
_array[constIndex];
_array[finalIndex];
_array[Some.index];

for (final element in _array) {
_array[element]; // Correct, depends on the loop
_array[mutableIndex]; // Correct, can be mutated
_array[Some.mutableIndex];
}
}

class Some {
static final index = 1;
static int mutableIndex = 1;
}

const constIndex = 1;
final finalIndex = 1;
var mutableIndex = 1;

Additional Resources