Skip to main content

avoid-collection-methods-with-unrelated-types

added in: 1.6.0
Pro+
preset: recommended

Warns when a collection method is used with an expression of an unrelated type.

Using unrelated types to access collection items or perform some operation (e.g. a contains check) will always result in null or false (depending on the used method or access type).

⚙️ Config

Set strict (default is true) to exclude dynamic and Object types (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-collection-methods-with-unrelated-types:
strict: true

Example

❌ Bad:

final map = Map<int, String>();
map["str"] = "value"; // LINT: Avoid collection methods with unrelated types.
map.containsKey("str"); // LINT: Avoid collection methods with unrelated types.
map.remove("str"); // LINT: Avoid collection methods with unrelated types.

final set = {10, 20, 30};
set.contains("str"); // LINT: Avoid collection methods with unrelated types.
set.containsAll(Iterable<String>.empty()); // LINT: Avoid collection methods with unrelated types.
set.difference(<String>{}); // LINT: Avoid collection methods with unrelated types.
set.lookup("str"); // LINT: Avoid collection methods with unrelated types.

✅ Good:

final map = Map<int, String>();
map[42] = "value"; // Correct, key is 'int'
map.containsKey(42);
map.remove(42);

final set = {10, 20, 30};
set.contains(42);
set.containsAll(Iterable<int>.empty());
set.difference(<int>{});
set.lookup(42);

Example with "strict"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-collection-methods-with-unrelated-types:
strict: false

✅ Good:

void fn() {
dynamic key = 1;

final regularMap = Map<int, String>();
regularMap[key] = "value"; // Correct, key is "dynamic"
}

Additional Resources