Skip to content

avoid_map_keys_contains

v0.4.0 Warning Fix Collection & Type

Using map.keys.contains(key) iterates through all keys to check for existence, while map.containsKey(key) performs a direct hash lookup. This rule catches the slower pattern and suggests the more efficient alternative.

Map.keys returns an Iterable that must be traversed linearly to check for a key, making it O(n). Map.containsKey() uses the map’s hash table directly and runs in O(1). For large maps, the performance difference is significant.

See also: Map.containsKey

void example() {
final map = {'hello': 'world', 'foo': 'bar'};
// Use containsKey() instead
final exists = map.keys.contains('hello');
// Also in conditions
if (map.keys.contains('foo')) {
print('found');
}
}
void example() {
final map = {'hello': 'world', 'foo': 'bar'};
final exists = map.containsKey('hello');
if (map.containsKey('foo')) {
print('found');
}
}

To disable this rule:

plugins:
many_lints:
diagnostics:
avoid_map_keys_contains: false