Skip to main content

avoid-accessing-collections-by-constant-index

added in: 1.10.0
preset: recommended

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

Example

❌ Bad:

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

void func() {
for (final element in _array) {
_array[0]; // LINT
_array[element];
_array[constIndex]; // LINT
_array[finalIndex]; // LINT
_array[mutableIndex];
_array[Some.index]; // LINT
_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];
_array[constIndex];
_array[finalIndex];
_array[Some.index];

for (final element in _array) {
_array[element];
_array[mutableIndex];
_array[Some.mutableIndex];
}
}

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

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