prefer_for_elements_to_map_fromiterable
Use 'for' elements when building maps from iterables.
Description
#The analyzer produces this diagnostic when Map.fromIterable
is used to build a map that could be built using the for
element.
Example
#The following code produces this diagnostic because fromIterable
is being used to build a map that could be built using a for
element:
dart
void f(Iterable<String> data) {
Map<String, int>.fromIterable(
data,
key: (element) => element,
value: (element) => element.length,
);
}
Common fixes
#Use a for
element to build the map:
dart
void f(Iterable<String> data) {
<String, int>{
for (var element in data)
element: element.length
};
}
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-05-08. View source or report an issue.