Reputation: 41
I am new in flutter/ dart and working in a web service powered flutter app. I am currently facing a problem in Mapping and displaying Nested JSON data.
The JSON which i need to deal is provided from my local php server JSON format, i have tried and is working with code:
BD: "Bangladesh"
BE: "Belgium"
BF: "Burkina Faso"
BG: "Bulgaria"
code:
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 widget to display data:
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)),
)
],
)
);
I have the server side php code working and is supplying the following json data on POST request
JSON data i want to map and display similarly as above:
{
"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"
},
}
Connection Post request code:
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.');
}
}
I want the to show the JSON as profile cards for many staff profiles (in card) i am getting from server in ListView Builder
Upvotes: 1
Views: 1965
Reputation: 41
After a few hit and trials i figured out that all i needed was a nested MAP in dart,
Map[key][subkey]
The following code solved my problem:
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)),
)
],
)
);
Upvotes: 3