> 在飞镖,dart"/>

首页 > 解决方案 > 地图到地图> 在飞镖

问题描述

我正在尝试转换Map<String,dynamic>Map<String, Map<String, String>>Dart

Map<String,dynamic> oldMap = querySnapshot.docs.first.data()["cach"];

Map<String, Map<String, String>> newMap = oldMap.map((a, b) => MapEntry(a, b as Map<String, String>)); 

但我得到一个错误:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast

标签: dart

解决方案


import 'dart:convert';

const rawData = '''
{"a": {"b": "c"}, "d":{"e": "f"}}
''';

Map<String, String> convert(Map<String, dynamic> data) {
  return Map<String,String>.fromEntries(data.entries.map<MapEntry<String,String>>((me) => MapEntry(me.key, me.value)));
}

void main(List<String> args) {
  var oldMap = jsonDecode(rawData) as Map<String, dynamic>;
  var newMap = Map.fromEntries(oldMap.entries.map((me) => MapEntry(me.key, convert(me.value))));
 
  print(newMap.runtimeType);
}

结果:

_InternalLinkedHashMap<String, Map<String, String>>

推荐阅读