prefer_for_elements_to_map_fromIterable
Prefer ‘for’ elements when building maps from iterables.
This rule is available as of Dart 2.3.0.
Rule sets: recommended, flutter
This rule has a quick fix available.
Details
When building maps from iterables, it is preferable to use ‘for’ elements.
Using ‘for’ elements brings several benefits including:
- Performance
- Flexibility
- Readability
- Improved type inference
- Improved interaction with null safety
BAD:
Map<String, WidgetBuilder>.fromIterable(
kAllGalleryDemos,
key: (demo) => '${demo.routeName}',
value: (demo) => demo.buildRoute,
);
GOOD:
return {
for (var demo in kAllGalleryDemos)
'${demo.routeName}': demo.buildRoute,
};
GOOD:
// Map<int, Student> is not required, type is inferred automatically.
final pizzaRecipients = {
...studentLeaders,
for (var student in classG)
if (student.isPassing) student.id: student,
};
Usage
To enable the prefer_for_elements_to_map_fromIterable
rule,
add prefer_for_elements_to_map_fromIterable
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- prefer_for_elements_to_map_fromIterable