I'm trying to learn the Dart programming language.
I didn't understand the Map.fromEntries() factory constructor. Looking for an usage example.
link : Map.fromEntries()
I'm trying to learn the Dart programming language.
I didn't understand the Map.fromEntries() factory constructor. Looking for an usage example.
link : Map.fromEntries()
The Map.fromEntries constructor is intended to use for creating a map by generating a sequence of pairs.
You can use it to create a map from another map as Map.fromEntries(otherMap.entries), but that's wasteful. You can just do Map.from(otherMap).
It's more interesting if you calculate the entries from something else (which may or may not itself be entries). Example:
Iterable<int> someInts = [2, 7, .... ];
var squareMap = Map.fromEntries(someInts.map((n) => MapEntry(n, n * n)));
print(squareMap[7]); // prints 49.
Or you can filter the entries somehow:
var filteredMap = Map.fromEntries(otherMap.entries.where((e) => e.key.isOdd));
You can often get the same effect by using Map.fromIterable or Map.fromIterables, it all depends on which primitives you have available. Filtering the entries of an existing map is particularly easy using Map.fromEntries, whereas creating a new map from scratch is probably equally easy using Map.fromIterable or Map.fromIterables.