Contents

prefer_for_elements_to_map_fromIterable

Contents

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