Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart map to another map through map function

Tags:

dart

Suppose I have a Map:

Map<String, int> source = {'a':1, 'b':2, 'c':3};

I want to get this:

Map<String, int> expected = {'a': 1, 'b':4, 'c':9 };

I want to achieve the result using map function:

Map<String,int> actual = source.map((key,value)=> {key: value * value});

However, I got this error:

The return type 'Map<String, int>' isn't a 'MapEntry<String, int>', as required by the closure's context

Can't we use the map function of map to get another map like this?

like image 270
ron Avatar asked Aug 29 '26 15:08

ron


1 Answers

The mapping method should return a MapEntry instance since you can change both the key and value. So your code should instead be something like:

void main() {
  final source = {'a': 1, 'b': 2, 'c': 3};
  final actual = source.map((key, value) => MapEntry(key, value * value));
  print(actual); // {a: 1, b: 4, c: 9}
}
like image 139
julemand101 Avatar answered Aug 31 '26 07:08

julemand101