How to pass a list of json to body of http request (post) in Flutter? How to pass a list of json to body of http request (post) in Flutter? dart dart

How to pass a list of json to body of http request (post) in Flutter?


You can do it in a very simple way. Create payment.dart file and copy paste the below code classes.

class PaymentList {PaymentList(this.payments);List<Payment> payments;Map<String, dynamic> toJson() => <String, dynamic>{    'payment_slips': payments,  };}class Payment {Payment({this.name, this.personalId});String name;String personalId;Map<String, dynamic> toJson() => <String, dynamic>{    'personal_id': personalId,    'name': name,  };}

Now you can covert it to the required json format using below code. For example I am creating a dummy list:

final PaymentList paymentList =    PaymentList(List<Payment>.generate(2, (int index) {  return Payment(name: 'Person $index', personalId: '$index');}));final String requestBody = json.encoder.convert(paymentList);

The requestBody variable will have the json string as follows:

  {"payment_slips": [    {        "personal_id": "0",        "name": "Person 0"    },    {        "personal_id": "1",        "name": "Person 1"    }  ]}

Now you can call the api:

var response = await http.post(url, body: requestBody}

Note: Please import the below package, which will be required to access json:

import 'dart:convert';


So it looks like you are not getting the JSON you expect. I have put together some code to show you how to get the body you want.

Link to run in DartPad https://dartpad.dartlang.org/3fde03078e56efe13d31482dea8e5eef

    class PaymentSlipes {      String name;      String personaId;      ObjPayment({this.name, this.personaId});      //You create this to convert your object to JSON      Map<String, dynamic> toJson() => {'name': name, 'personaId': personaId};    }    // This method is needed to convert the list of ObjPayment into an Json Array    List encondeToJson(List<PaymentSlipes> list) {      List jsonList = List();      list.map((item) => jsonList.add(item.toJson())).toList();      return jsonList;    }    // This is an example and this code will run in DartPad link above    void main() {      PaymentSlipes objPayment = PaymentSlipes(name: "Douglas", personaId: "123425465");      PaymentSlipes objPayment2 = PaymentSlipes(name: "Dave", personaId: "123425465;      PaymentSlipes objPayment3 = PaymentSlipes(name: "Mike", personaId: "123425465");      var list = [objPayment, objPayment2, objPayment3];      // This is the mapping of the list under the key payment_slips as per your example and the body i would pass to the POST      var finalJson = {"payment_slips": encondeToJson(list)};      print(finalJson);    }