chongman
chongman

Reputation: 2507

Dart: How to use the Map.map() method/function

I am trying to use the "map" method/function on a Map object in Dart. (I know, it's a mouthful, and hard to search in google).

https://api.flutter.dev/flutter/dart-core/Map/map.html

It's essentially like List.map, generating a new Map by applying conversions to the keys and value pairs.

Why might you use this? Maybe you need to rename some keys in your Map object.

Example Code / Error

void main() {
  Map myMap={"a":1, "b":2};
  print(myMap);
  
  print(myMap.map((k,v) {
    k=k+k;
    v=v*10;
    return {k:v};

  // I expect { aa:10,bb:20 }
  }));
}

I get a compilation error:

Error: A value of type 'Map<dynamic, dynamic>' can't be returned from a function with return type 'MapEntry<dynamic, dynamic>'.
 - 'Map' is from 'dart:core'.
 - 'MapEntry' is from 'dart:core'.
    return {k:v};
           ^
Error: Compilation failed.

Since I didn't find any examples online, I'm writing up the answer here.

Upvotes: 5

Views: 5522

Answers (1)

chongman
chongman

Reputation: 2507

In the code above, I expected it to take the separate Map items in the return statement and merge them into one Map object. But, instead, it gives an error. It wants a MapEntry object.

So the correct code is

void main() {
  Map myMap={"a":1, "b":2};
  print(myMap);
  
  print(myMap.map((k,v) {
    k=k+k;
    v=v*10;
    return MapEntry(k, v);
  }));
  
  print(myMap);
}

Furthermore, the console output is

{a: 1, b: 2}
{aa: 10, bb: 20}
{a: 1, b: 2}

Appendix on variable passing

Note: I worried (and wondered) if modifying the k and v variables in the convert function would modify anything in the original object. So, I checked. No change when the keys and values are immutable objects (like strings and numbers).

If, instead, you have a mutable object, like a map, then it does change that object.

See, for example:

void main() {
  Map myMap={"a":1, "b":2};
  print(myMap);
  
  print(myMap.map((k,v) {
    k=k+k;
    v=v*10;
    return MapEntry(k, v);
  }));
  
  print(myMap);
  
  print("======");
  
  Map myMap2={"c":1, "d":{"changed": "no"}};
  print(myMap2);
  
  print(myMap2.map((k,v) {
    k=k+k+k;
    if (k=="ddd") {
      v["changed"]="yes";
    }
    return MapEntry(k, v);
  }));
  
  print(myMap2);
}

Which returns

{a: 1, b: 2}
{aa: 10, bb: 20}
{a: 1, b: 2}
======
{c: 1, d: {changed: no}}
{ccc: 1, ddd: {changed: yes}}
{c: 1, d: {changed: yes}}

See https://dartpad.dev/?id=57382792d2fa7a50566c228678a1d4da&null_safety=true

Upvotes: 3

Related Questions