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.
Why use this rule
Section titled “Why use this rule”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 = {'lat': 52.2, 'lon': 21.0};
// Use containsKey() instead final exists = map.keys.contains('lat');
// Also in conditions if (map.keys.contains('foo')) { print('found'); }}void example() { final map = {'lat': 52.2, 'lon': 21.0};
final exists = map.containsKey('lat');
if (map.containsKey('foo')) { print('found'); }}Configuration
Section titled “Configuration”This rule is in the recommended preset, so it is on with
preset: recommended or preset: opinionated. Add it to preset: core with
avoid_map_keys_contains: true.
To turn it off:
rules: avoid_map_keys_contains: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_missing_enum_constant_in_map— Cover every enum constant in a map keyed by that enum.map_keys_ordering— Keep map literal keys in a configured order.avoid_accessing_collections_by_constant_index— Avoid accessing a collection by a constant index inside a loop.avoid_collection_equality_checks— Avoid comparing collections with == or != as it checks reference equality, not contents.