prefer_for_elements_to_map_fromIterable
Prefer for
elements when building maps from iterables.
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:
dart
Map<String, WidgetBuilder>.fromIterable(
kAllGalleryDemos,
key: (demo) => '${demo.routeName}',
value: (demo) => demo.buildRoute,
);
GOOD:
dart
return {
for (var demo in kAllGalleryDemos)
'${demo.routeName}': demo.buildRoute,
};
GOOD:
dart
// Map<int, Student> is not required, type is inferred automatically.
final pizzaRecipients = {
...studentLeaders,
for (var student in classG)
if (student.isPassing) student.id: student,
};
Enable
#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:
analysis_options.yaml
yaml
linter:
rules:
- prefer_for_elements_to_map_fromIterable
If you're instead using the YAML map syntax to configure linter rules, add prefer_for_elements_to_map_fromIterable: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
prefer_for_elements_to_map_fromIterable: true
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-03-07. View source or report an issue.