[Solved] Dart - How to convert nested Map<dynamic, dynamic> to Map<String, dynamic>

Question

Asked by Adam S on December 21, 2021 (source).

I know how to convert Map<dynamic, dynamic> to Map<String, dynamic> using Map.from() method. But what if I have unspecified number of nested Maps inside? How to convert all potential children as well from Map<dynamic, dynamic> to Map<String, dynamic>?

Answer

Question answered by fravolt (source).

You could use a recursive approach to this problem, where all map values of type Map are recursively converted as well.

// recursively convert the map
Map<String, dynamic> convertMap(Map<dynamic, dynamic> map) {
  map.forEach((key, value) {
    if (value is Map) {
      // it's a map, process it
      value = convertMap(value);
    }
  });
  // use .from to ensure the keys are Strings
  return Map<String, dynamic>.from(map);
  // more explicit alternative way:
  // return Map.fromEntries(map.entries.map((entry) => MapEntry(entry.key.toString(), entry.value)));
}

// example nested map with dynamic values
Map<dynamic, dynamic> nestedMap = {
  'first': 'value',
  'second': {
    'foo': 'bar',
    'yes': 'ok',
    'map': {'some': 'value'},
  }
};

// convert the example map
Map<String, dynamic> result = convertMap(nestedMap);
print(result);
DART FLUTTER
SHARE: