Marzook
Marzook

Reputation: 391

How to fetch complex Json objects in flutter?

This is the API response I want to fetch "installments" array values

 {
 "unit":
      { 
    .....
      },
 "receipt": 
 {
   .....
 },
"instalments": [
    {
        "payment_type": "5",
        "amount": "3",
        "bank_name": "ABU DHABI COMMERCIAL BANK",
        "paid_date": "2020-08-07 01:11:02",
        "status": "0",
    }
    {
        "payment_type": "5",
        "amount": "3",
        "bank_name": "ABU DHABI COMMERCIAL BANK",
        "paid_date": "2020-08-07 01:11:02",
        "status": "0",
    }
    ]
  }

I use this mode class to get value from API

class PaymentInstallment {
 String payment_type;
 String payment_amount;
 String payment_date;
 String status;

 PaymentInstallment(
     {this.payment_type, this.payment_amount, this.payment_date, this.status});

  factory PaymentInstallment.fromjson(Map<String, dynamic> json) {
    return PaymentInstallment(
    payment_type: json['payment_type'],
    payment_amount: json['amount'],
  payment_date: json['paid_date'],
  status: json['status'],
       );
     }
    }

this is my list and adding the response from the server to it

   List<PaymentInstallment> _list = [];


  final response = await http.get(
    url,
    headers: {"Accept": "application/json", "Authorization": token},
   );
   var response = jsonDecode(response.body);
    setState(() {
    for (Map temppayment in response) {
      _list.add(PaymentInstallment.fromjson(temppayment));
     }
     });

how can i all array value from "instalments" array and add to the list

Upvotes: 0

Views: 55

Answers (1)

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12693

Try this

var response = jsonDecode(response.body);
List installmentList = List.from(response["installment"]);
setState((){
   _list = installmentList.map((f) => PaymentInstallment.fromJson(f)).toList();
});

If it isn't looping try this

List tempList = [];
installmentList.forEach((f) => tempList.add(f));
setState((){
  _list = tempList;
});

Upvotes: 1

Related Questions