Home > Software engineering >  converting a list to a map, Why does DART ask you not to use the Map.fromIterable method?
converting a list to a map, Why does DART ask you not to use the Map.fromIterable method?

Time:09-27

// Convert a list to a map type.
test() {
  var y = [
    [10, 20],
    [30, 43],
    [51, 60]
  ];
  var mapOne = Map.fromIterable(y, key: (v) => v[0], value: (v) => v[1]);
  var mapTwo = {for (final x in y) x[0]: x[1]};
  print(mapOne); //outputs {10: 20, 30: 43, 51: 60}
  print(mapTwo); //outputs {10: 20, 30: 43, 51: 60}
}

As you can see from the above code, both syntaxes result in same output, yet dart gives you a warning saying

prefer for elements when building maps from iterables

So my question is why does dart prefer the syntax of mapTwo over mapOne?

If thats the case whats the point of having methods like Map.fromIterable if dart don't want you using them.

CodePudding user response:

Map.fromIterable existed before the collection elements feature existed. Removing it now would be a breaking change. The warning comes from a lint and not from the language. It's a style preference.

Source: https://github.com/dart-lang/language/issues/2521#issuecomment-1257199865

CodePudding user response:

Using 'for' elements brings several benefits including:

Performance

Flexibility

Readability

Improved type inference

Improved interaction with null safety

See prefer_for_elements_to_map_fromIterable for details.

CodePudding user response:

I think you should open an issue in this repository on Github and ask your question.

  • Related