Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart, a nicer way of mapping maps?

Tags:

map

dart

I like the .map((item){/*mapper*/}) that is on the Iterable classes, but the Map class doesn't appear to implement an analogous method. When I want to do the following, I have to create an blank instance and then forEach over the existing Map I want to map to the new instance type:

void noSuchMethod(Invocation inv){
  if(inv.isMethod){
    var namedArguments = new Map<String, dynamic>();
    inv.namedArguments.forEach((k, v){
      namedArguments[MirrorSystem.getName(k)] = v;
    });
    return;
  }
  super.noSuchMethod(inv);
}

Is there a nicer way of mapping Maps? It seems a litle odd that there is a forEach((v){}) for Iterables and a forEach((k, v){}) for Maps but not a map((k, v){}) for Maps.

like image 370
Daniel Robinson Avatar asked Nov 29 '22 00:11

Daniel Robinson


2 Answers

Just for info

Now you can use a special method that is in every instance of the Map class.

final dict = { "id": 1, "name": "Alex", "isAdmin": true };
// A simple map, that contains a user's info

dict.map((key, value) => MapEntry(key, value.toString()));
// Here we can transform the key and the value of this map

print(dict);
// { "id": "1", "name": "Alex", "isAdmin": "true" }
// All fields are strings now
like image 126
R. Shirkhanov Avatar answered Dec 05 '22 01:12

R. Shirkhanov


This should do what you want:

Map m = {'1': 1, '2':2 };
var newMap = new Map.fromIterable(m.keys, key: (k) => k , value: (v) => m[v] * 5 );
like image 25
Günter Zöchbauer Avatar answered Dec 05 '22 01:12

Günter Zöchbauer