从Dart地图中提取地图

时间:2020-04-01 10:46:52

标签: dart

我将如何转换此地图

{
  "country": "uk",
  "postcode": "500",
  "suburbs": [
    {
      "code": "liverpool",
      "name": "liverpool"
    },
    {
      "code": "merseyside",
      "name": "merseyside"
    }
  ]
}

{
  "country": "uk",
  "postcode": "500",
  "suburb":"liverpool"

}

1 个答案:

答案 0 :(得分:1)

我想您首先自己尝试过,但是由于地图包含不同类型的元素而导致类型问题。

您可以通过编译器知道类型为dynamic(禁用类型安全性)的方式声明Map:

void main() async {
  final mapFrom = <String, dynamic>{
    "country": "uk",
    "postcode": "500",
    "suburbs": [
      {"code": "liverpool", "name": "liverpool"},
      {"code": "merseyside", "name": "merseyside"}
    ]
  };

  final mapTo = {
    "country": mapFrom["country"],
    "postcode": mapFrom["country"],
    "suburbs": mapFrom["suburbs"][0]["code"]
  };

  print(mapTo); // {country: uk, postcode: uk, suburbs: liverpool}
}

如果要修改地图,请执行以下操作:

  final mapTo = Map.of(mapFrom);
  mapTo["suburbs"] = mapTo["suburbs"][0]["code"];