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

时间:2019-04-25 16:27:07

标签: json dart flutter

我是flutter / dart的新手,正在使用基于Web服务的flutter应用程序。我目前在映射和显示嵌套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中的服务器获取的许多职员资料的个人资料卡(在卡片中)

1 个答案:

答案 0 :(得分:0)

几经周折,我发现我所需要的只是在dart中嵌套的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)),
                    )
                  ],
        )
);