繁体   English   中英

如何在Dart / flutter中映射和显示嵌套的JSON?

[英]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.

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