如何访问 Dart 中嵌套映射中给定键的值?
How do I access the value of a given key in a nested Map in Dart?
我是 Dart 的新手,我一直在尝试访问以下代码中“farm_size”键的值,但没有成功。我最多可以访问这样的“农场”
print(myData1[0]["farms"]);
但没有进一步。任何帮助将不胜感激。谢谢
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"]);
}
在farms
里面,有一个更多地图的列表,要访问这些地图,你需要指定你的地图的索引,比如我们要获取第一张地图,我们输入:
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
如果你在 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']);
}
试试这个
List m = myData1[0]['farms'] as List;
print(m[0]['id']);
我是 Dart 的新手,我一直在尝试访问以下代码中“farm_size”键的值,但没有成功。我最多可以访问这样的“农场”
print(myData1[0]["farms"]);
但没有进一步。任何帮助将不胜感激。谢谢
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"]);
}
在farms
里面,有一个更多地图的列表,要访问这些地图,你需要指定你的地图的索引,比如我们要获取第一张地图,我们输入:
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
如果你在 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']);
}
试试这个
List m = myData1[0]['farms'] as List;
print(m[0]['id']);