Skip to content

avoid_collection_methods_with_unrelated_types

v0.3.0WarningConfigurableCollection & Type

Calling collection methods like contains(), remove(), or containsKey() with an argument whose type is unrelated to the collection’s type parameter will always return null, false, or -1. This indicates a logical error since Dart’s type system allows it due to these methods accepting Object?.

Methods like List.contains() and Map.containsKey() accept Object? for historical reasons, so the compiler won’t catch type mismatches. Passing a String to List<int>.contains() compiles fine but always returns false, hiding a bug.

See also: Dart generics | Dart lint: collection_methods_unrelated_type

void example() {
final list = <int>[1, 2, 3];
// String argument on int list
list.contains('a');
list.remove('a');
final set = <int>{1, 2, 3};
// String argument on int set
set.contains('a');
set.lookup('a');
final map = <int, String>{};
// String key on int-keyed map
map.containsKey('a');
// int value on String-valued map
map.containsValue(42);
// String key on int-keyed map
final value = map['a'];
map.remove('a');
}
void example() {
final list = <int>[1, 2, 3];
list.contains(1);
list.remove(2);
list.indexOf(3);
final set = <int>{1, 2, 3};
set.contains(1);
final map = <int, String>{};
map.containsKey(1);
map.containsValue('hello');
final value = map[1];
map.remove(1);
// Subtypes are fine
final numList = <num>[1, 2, 3];
numList.contains(42); // int is subtype of num
// Dynamic is allowed with the default configuration.
// It is reported when strict: true is enabled.
dynamic unknown = 42;
list.contains(unknown);
}

This rule is in the core preset, so it is on with preset: core, preset: recommended or preset: opinionated.

To turn it off:

many_lints.yaml
rules:
avoid_collection_methods_with_unrelated_types: false

To keep the rule on but skip certain paths, use per-rule exclude.

analysis_options.yaml
many_lints:
rules:
avoid_collection_methods_with_unrelated_types:
strict: true
Option Type Default Description
strict bool false Also report a dynamic argument passed where a known element type is expected