prefer_for_elements_to_map_fromIterable
Prefer for
elements when building maps from iterables.
This rule is available as of Dart 2.3.
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:
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,
};
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:
analysis_options.yaml
yaml
linter:
rules:
- prefer_for_elements_to_map_fromIterable
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。