[英]How to Map and display nested JSON in Dart/ flutter?
我是flutter / dart的新手,並且正在使用Web服務驅動的撲動應用程序。 我目前在映射和顯示嵌套JSON數據時遇到問題。
我需要處理的JSON是從我的本地php服務器JSON格式提供的,我已經嘗試過並且正在使用代碼:
BD: "Bangladesh"
BE: "Belgium"
BF: "Burkina Faso"
BG: "Bulgaria"
碼:
Map _countries = new Map();
void _getData() async {
var url = 'http://country.io/names.json';
var response = await http.post(url);
if (response.statusCode == 200) {
setState(() => _countries = json.decode(response.body));
debugPrint('Loaded ${_countries.length} data.');
}
}
Flutter小部件顯示數據:
return Card(
child: new Row(
children: <Widget>[
Expanded(
child: new Text(
'${key} : ',
style: TextStyle(fontSize: 28.0),
),
),
Expanded(
child: new Text(_counties[key],
style: TextStyle(fontSize: 28.0)),
)
],
)
);
我有服務器端PHP代碼工作,並在POST請求上提供以下json數據
我希望以與上面類似的方式映射和顯示JSON數據:
{
"Employee_id1": {
"first_name": "Staff",
"last_name": "EFGH",
"contact": "1223234555",
"designation": "des1",
"department": "d1",
"picture": "http://i.pravatar.cc/300"
},
"Employee_id2": {
"first_name": "Staff",
"last_name": "EFGH",
"contact": "1223234555",
"designation": "des1",
"department": "d2",
"picture": "http://i.pravatar.cc/300"
},
}
連接發布請求代碼:
void _getData() async {
var url = 'http://myIP/file.php';
var response = await http.post(url, body:
{"staffprofiles":"showStaffs"});
if (response.statusCode == 200) {
setState(() => _staffs = json.decode(response.body));
debugPrint('Loaded ${_staffs.length} staff profiles.');
}
}
我希望將JSON顯示為我從ListView Builder中的服務器獲取的許多員工配置文件(卡中)的配置文件卡
經過一些打擊和試驗,我發現我所需要的只是一個嵌套的飛鏢MAP,
Map[key][subkey]
以下代碼解決了我的問題:
return Card(
child: new Row(
children: <Widget>[
Expanded(
child: new Text(
'${key} : ',
style: TextStyle(fontSize: 28.0),
),
),
Expanded(
child: new Text(_employees[key]["first_name"],
style: TextStyle(fontSize: 28.0)),
)
],
)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.