avoid_collection_methods_with_unrelated_types
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?.
Why use this rule
Section titled “Why use this rule”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);}Turning this rule off
Section titled “Turning this rule off”This rule is in the core preset, so it is on with preset: core,
preset: recommended or preset: opinionated.
To turn it off:
rules: avoid_collection_methods_with_unrelated_types: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Options
Section titled “Options”many_lints: rules: avoid_collection_methods_with_unrelated_types: strict: truerules: 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 |
Related rules
Section titled “Related rules”avoid_unsafe_collection_methods— Check for emptiness before using first, last, single or reduce.avoid_collection_equality_checks— Avoid comparing collections with == or != as it checks reference equality, not contents.avoid_duplicate_collection_elements— Don’t repeat the same element in a collection literal.avoid_unrelated_type_casts— Don’t cast or type-test between unrelated types.