Skip to main content

avoid-mutating-constant-collections

effort: 5m
pro+

Warns when a constant collection is being mutated.

Trying to add/remove elements to a constant collection will throw a runtime exception.

Example

❌ Bad:

const global = [1, 2, 3];

class SomeClass {
static const set = {1, 2, 3};

final list = const [1, 2, 3];

void fn() {
// LINT: Avoid mutating constant collections.
// This invocation will throw a runtime exception.
list.add(1);
// LINT: Avoid mutating constant collections.
// This invocation will throw a runtime exception.
global.add(2);
// LINT: Avoid mutating constant collections.
// This invocation will throw a runtime exception.
set.add(3);
}
}

✅ Good:

class SomeClass {
static final set = {1, 2, 3}; // now mutable

final list = [1, 2, 3]; // now mutable

void fn() {
list.add(1);
set.add(3);
}
}

Additional Resources