0

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: "" );

1 Answer 1

1
  1. Create Item class.
class Item {
  String description;
  int id;

  Item({this.description, this.id});

}
  1. Define fromJson constructor for Item class
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);
        },
      );
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.