While it is possible to build a Map from an Iterable using Map.fromIterable, writing an explicit
for loop with for elements should be used instead.
The main reason to prefer for elements is that it can be optimized by the Dart compiler for performance, depending on the iterable
being visited.
Moreover, for elements are more idiomatic and generally easier to understand than Map.fromIterable, which requires
explicit map type upfront, as well as the input iterable and two different lambda functions as parameters.
Map<String, int>.fromIterable( // Explicit Map<String, int> type required
inputIterable,
key: (item) => ..., // Key generator
value: (item) => ..., // Value generator
);
On the other hand, for elements are more flexible, look like normal for loops, and support better inference of the
resulting Map type.
{
for (final item in inputIterable)
'The value is $v': v // Implicit Map<String, int> type inference
}
Exceptions
The rule only applies to the fromIterable factory method of Map. It does not apply to other fromIterable
methods, such as the one from LinkedHashMap<T, U> in dart:collection.
Moreover, it only applies when all the arguments of the Map.fromIterable call are provided. If either the key or the
value parameter is omitted, the rule does not apply.
Map<int, int>.fromIterable(l1, key: (item) => ...); // OK
Map<int, int>.fromIterable(l1, value: (item) => ...); // OK
The rule also does not apply when the key and value parameters are not inline function expressions, but variables defined
elesewhere in the code.
final key = (item) => ...;
final value = (item) => ...;
Map<int, int>.fromIterable(l1, key: key, value: value);