Reputation: 319
I have this item and want loop "description" and "id" objects into array list;
{
"code": 200,
"message": "OK",
"payload": {
"items": [
{
"description": "test",
"icon": "",
"id": 25
},
{
"description": "TEST PACKAGE",
"icon": "",
"id": 26
},
{
"description": "TEST PACKAGE 2",
"icon": "",
"id": 26
}
]
}
}
Model
Item(decription: "" , id: "" );
Upvotes: 0
Views: 47
Reputation: 4763
class Item {
String description;
int id;
Item({this.description, this.id});
}
class Item {
String description;
int id;
Item({this.description, this.id});
Item.fromJson(Map<String, dynamic> json) {
description = json['description'];
id = json['id'];
}
}
final response = await http.get("YOUR API");
// Convert response String to Map
final responseJson = json.decode(response.body);
List<Item> items = List();
if (responseJson != null && responseJson["payload"] != null) {
Map payload = responseJson["payload"];
if (payload["items"] != null) {
// Convert each item from Map to Item object and add it to the items List
payload["items"].forEach(
(v) {
final item = Item.fromJson(v);
items.add(item);
},
);
}
}
Upvotes: 1