简体   繁体   English

如何访问 Dart 中嵌套的 Map 中给定键的值?

[英]How do I access the value of a given key in a nested Map in Dart?

I am new in Dart and I have been trying to access the value of "farm_size" key in the following piece of code but unsuccessful.我是 Dart 的新手,我一直在尝试访问以下代码中“farm_size”键的值,但没有成功。 I can access up to "farms" like this我最多可以访问这样的“农场”

print(myData1[0]["farms"]);

But not any further.但没有进一步。 Any help will be appreciated.任何帮助将不胜感激。 Thanks.谢谢。

void main() {
  var myData1 = [
  {
    "id": 1,
    "first_name": "Jordan",
    "sur_name": "Zamunda",
    "member_n0": "AA1",
    "gender": "male",
    "phone": "123456789",
    "email": "jordan@example.com",
    "farms": [
      {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"},
      {"id": 2, "farm_name": "NORTH_FARM", "farm_size": "190 acres"}
    ]
  }
];

  print(myData1[0]["farms"]);

}

inside farms , there is a list of more maps, to access those maps, you need to specify the index of the map you, for example we want to get the first map, we type:farms里面,有一个更多地图的列表,要访问这些地图,你需要指定 map 你的索引,例如我们要获取第一个 map,我们输入:

print(myData1[0]["farms"][0]);
//this will print => {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"}

//to get the name of this farm, you use the key 'farm_name' now:
print(myData1[0]["farms"][0]['farm_name']);
//prints=> SOUTH_FARM

If you're running it in dartpad, this will work:如果你在 dartpad 中运行它,这将起作用:

void main() {
  
  var myData1 = [
  {
    "id": 1,
    "first_name": "Jordan",
    "sur_name": "Zamunda",
    "member_n0": "AA1",
    "gender": "male",
    "phone": "123456789",
    "email": "jordan@example.com",
    "farms": [
      {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"},
      {"id": 2, "farm_name": "NORTH_FARM", "farm_size": "190 acres"}
    ]
  }
];
  List<Map<String,dynamic>> _list = myData1[0]["farms"]as List<Map<String,dynamic>> ;
  
  print(_list[0]['farm_name']);


}

try this尝试这个

List m = myData1[0]['farms'] as List;

 print(m[0]['id']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM