I have a JSON object here:
{
"error": "0",
"message": "Succesfully fetched",
"data": [
{
"status": true,
"_id": "5df0b94841f0331baf1357bb",
"name": "test group",
"description": "test description",
"created_date": "2019-12-11T09:39:20.151Z",
"__v": 0
},
{
"status": true,
"_id": "5df0df507091683d2f1ad0cf",
"name": "new group",
"created_date": "2019-12-11T12:21:36.283Z",
"__v": 0
}
]
}
I want to fetch the name parameter under data to a DropDownMenuList
. I have a data model here:
class dataArray {
// final dynamic status;
final dynamic id;
final dynamic groupName;
// final dynamic description;
// final dynamic created_date;
// final dynamic v;
dataArray(this.groupName, this.id);
dataArray.fromJson(Map jsonMap)
: groupName = jsonMap['name'],
id = jsonMap['_id'];
Map toMapData(){
var mapGroup = new Map<String, dynamic>();
mapGroup["name"] = groupName;
mapGroup['_id'] = id;
return mapGroup;
}
}
Function to fetch:
Future<List<dataArray>> gettaskData() async {
List<dataArray> list;
String link = ""; //Cannot provide this due to confidentiality
var res = await http
.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
print(res.body);
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["data"] as List;
var error = data['error'];
print("this is error = $error");
print(rest);
list = rest.map<dataArray>((json) => dataArray.fromJson(json)).toList();
}
print("List Size: ${list.length}");
return list;
}
This method fetches the item successfully into a ListView.builder
widget but I am a bit lost on how to fetch this to a List<DropdownMenuItem<T>> items
.
I have tried to go through these solutions:
The first link seems to be fetching a list instead of a Map and the second displays a map whereas, in my JSON list, I have to display a value from a list of maps.
EDIT: based on the accepted answer, i have also modified the initJson
method to this -
Future initJson() async {
_list = await loadJsonFromAsset();
//print("Printing _List = ${_list[0].groupName}");
// if (_list.length > 0) {
setState(() {
for(int i =0; i<=_list.length - 1; i++) {
_selectedMenuItem = _list[i];
}
});
// }
}
this displayed the name parameter of every object present in the api.