avoid-collection-mutating-methods
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 (example).
Set methods
(default is [remove
, removeAt
, removeLast
, putIfAbsent
, update
]) to override the list of methods to check (example).
Set additional-methods
(default is empty) to add additional methods to the list of the default methods.
dart_code_metrics:
rules:
- avoid-collection-mutating-methods:
ignore-local: true
additional-methods:
- contains
Example
❌ Bad:
void main(List<int> list) {
// LINT: Avoid collection methods that mutate the initial collection. Try creating a new collection with an updated value instead.
list.remove(1);
// LINT: Avoid collection methods that mutate the initial collection. Try creating a new collection with an updated value instead.
list.addAll([1, 2, 3]);
// LINT: Avoid collection methods that mutate the initial collection. Try creating a new collection with an updated value instead.
list.removeAt(0);
final primitiveMap = Map<int, String>();
// LINT: Avoid collection methods that mutate the initial collection. Try creating a new collection with an updated value instead.
check(primitiveMap.addAll);
}
void check(void Function(Map<int, String>) callback) {}
✅ Good:
void main(List<int> list) {
final newList = [...list, ...[1, 2, 3]]; // Correct, new copy
}
Example with "ignore-local"
Config
dart_code_metrics:
rules:
- avoid-collection-mutating-methods:
ignore-local: false
❌ Bad:
void main() {
final list = [1, 2, 3];
list.remove(1); // LINT, local variables are now also highlighted
list.insert(0, 4); // LINT, local variables are now also highlighted
}
Example with "methods"
Config
dart_code_metrics:
rules:
- avoid-collection-mutating-methods:
methods:
- remove
❌ Bad:
void main(List<int> list) {
// LINT: Avoid collection methods that mutate the initial collection. Try creating a new collection with an updated value instead.
list.remove(1);
}
✅ Good:
void main(List<int> list) {
list.addAll([1, 2, 3]); // Correct, only "remove" is highlighted
}