Rules / Complexity / prefer-for-elements-to-map-from-iterable

prefer-for-elements-to-map-from-iterable

lint/complexity/prefer-for-elements-to-map-from-iterable
Same as prefer_for_elements_to_map_fromIterable · Dart lints

Flags Map.fromIterable(x, key: ..., value: ...).

A collection-for element inside a map literal — { for (final e in x) key(e): value(e) } — expresses the same transformation more directly, can be const, and avoids the intermediate closures Map.fromIterable requires. The rule fires on both Map.fromIterable(...) and new Map.fromIterable(...) when at least one positional argument and both the key: and value: named arguments are present.

Invalid

example.dartdart
void bad() {
  var a = Map.fromIterable(list, key: (e) => e, value: (e) => e * 2);
  var b = Map.fromIterable(items, key: (k) => k.id, value: (v) => v.name);
  var c = Map.fromIterable(nums, key: (n) => n.toString(), value: (n) => n);
  var d = Map.fromIterable(data, value: (e) => e, key: (e) => e.hashCode);
  var e = Map.fromIterable(xs, key: (x) => x, value: (x) => x);
}
Use a map literal with a 'for' element instead of 'Map.fromIterable'.
1void bad() {
2 var a = Map.fromIterable(list, key: (e) => e, value: (e) => e * 2);
Use a map literal with a 'for' element instead of 'Map.fromIterable'.
2 var a = Map.fromIterable(list, key: (e) => e, value: (e) => e * 2);
3 var b = Map.fromIterable(items, key: (k) => k.id, value: (v) => v.name);
Use a map literal with a 'for' element instead of 'Map.fromIterable'.
3 var b = Map.fromIterable(items, key: (k) => k.id, value: (v) => v.name);
4 var c = Map.fromIterable(nums, key: (n) => n.toString(), value: (n) => n);
Use a map literal with a 'for' element instead of 'Map.fromIterable'.
4 var c = Map.fromIterable(nums, key: (n) => n.toString(), value: (n) => n);
5 var d = Map.fromIterable(data, value: (e) => e, key: (e) => e.hashCode);
Use a map literal with a 'for' element instead of 'Map.fromIterable'.
5 var d = Map.fromIterable(data, value: (e) => e, key: (e) => e.hashCode);
6 var e = Map.fromIterable(xs, key: (x) => x, value: (x) => x);

Valid

example.dartdart
void good() {
  var a = {for (final e in list) e: e * 2};
  var b = Map.from(other);
  var c = Map.of(existing);
  var d = Map.fromEntries(entries);
  var e = Map.fromIterables(keys, values);
  var f = Map.fromIterable(list);
}

How to configure

Set the severity of prefer-for-elements-to-map-from-iterable in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "complexity": {
        "prefer-for-elements-to-map-from-iterable": "error"
      }
    }
  }
}