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

Same as prefer_for_elements_to_map_fromIterable in Dart lints

Path
lint/complexity/prefer-for-elements-to-map-from-iterable
Default
On (recommended)
Origin
Dart lints
Rule
359 of 512
recommended

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);
}

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

Set its severity in falcon.json. See the configuration guide.

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

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/complexity/prefer-for-elements-to-map-from-iterable: <reason>