Home > OS >  Flutter - Add maps to a map
Flutter - Add maps to a map

Time:11-05

Suppose there are two maps.

Map map01 = {
  'name': 'Peter',
  'age': 30,
}

Map map02 = {
  'name': 'Mark',
  'age': 25,
}

And there's another map called Map map1.

I need to add these map01 and map02 to map1.

i. e.

Map map1 = {
  map01: {
    'name': 'Peter',
    'age': 50,
  },
  map02: {
    'name': 'Mark',
    'age': 25,
  },
}

How can I do this?

CodePudding user response:

The key isn't getting from variable name. It is generating from map${(i 1).toString().padLeft(2, "0")}.

You can do something like this

    Map map01 = {
      'name': 'Peter',
      'age': 30,
    };

    Map map02 = {
      'name': 'Mark',
      'age': 25,
    };

    final myMaps = [map01, map02];
    final result = {};

    for (int i = 0; i < myMaps.length; i  ) {
      final k = "map${(i   1).toString().padLeft(2, "0")}";
      result.addAll({k: myMaps[i]});
    }
    print(result);
    //{map01: {name: Peter, age: 30}, map02: {name: Mark, age: 25}}
  
  • Related