Skip to main content

avoid-collection-mutating-methods

added in: 1.11.0
⚙️

Warns when a mutating method is called on a collection.

Mutating collections can lead to unexpected side effects when the collection is passed from an outer scope (for example, as an argument) and is later used in other functions. Consider creating a new collection instead of changing an existing one.

By default triggers on every method that has a void return type, as well as for methods in the methods config option.

⚙️ Config

Set ignore-local (default is true) to exclude local variables.

Set methods (default is [remove, removeAt, removeLast, putIfAbsent, update]) to override the list of methods to check.

Set additional-methods (default is empty) to add additional methods the list of methods to check.

dart_code_metrics:
...
rules:
...
- avoid-collection-mutating-methods:
ignore-local: true
additional-methods:
- contains

Example

❌ Bad:

void main {
final list = [1, 2, 3];

list.remove(1); // LINT
list.insert(0, 4); // LINT
list.addAll([1, 2, 3]); // LINT
list.removeAt(0); // LINT
list.shuffle(); // LINT

final primitiveMap = Map<int, String>();
check(primitiveMap.addAll); // LINT
}

void check(void Function(Map<int, String>) callback) {}

✅ Good:

void main {
final list = [1, 2, 3];

final newList = [...list, ...[1, 2, 3]];
}