Home > Mobile >  How to post json with nested json data using http in flutter?
How to post json with nested json data using http in flutter?

Time:12-06

I want to post json data that contains another json data into API using flutter with http

This is a sample of the data that I want to send

{sales_representative: 1,
 doctor: 1,
 remark: My Remark,
 date: 2021-12-05,
medicines: [
{medicine: 1,
 quantity_type: Tablet,
 quantity: 55
},
 {medicine: 1,
 quantity_type: Tablet,
 quantity: 5
}
]
}

And this is my API method

static Future postSale(body) {
    return http.post(Uri.parse('http://192.168.56.1:8000/api/sales/'),
        body: body);
  }

But flutter gives my this error:

Unhandled Exception: type 'List<Map<String, dynamic>>' is not a subtype of type 'String' in type cast

CodePudding user response:

I found what was my problem:

  1. I did not wrap the body with jsonEncode.
  2. I did not specify the header.

This is what I did to let it work.

return http.post(Uri.parse('http://192.168.56.1:8000/api/sales/'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode(body));
  }

CodePudding user response:

Please do this way.

var data ={};
   var medicines = [];
   var medicineData ={};  
  
  data["sales_representative"] = 1;
  data["doctor"] =1;
  data["remark"]="my remarks";
  data["date"] = "2021-12-05";
  
  for(int i=0;i<2; i  )
  {
       medicineData ={}; 
       medicineData["medicine"] =1;
       medicineData["quantity_type"] = "Tablet";
       medicineData["quantity"] =5;
    
      medicines.add(medicineData);
  }
  
  data["medicines"] = medicines;

and pass to this api request like this

http.post(Uri.parse('apiUrl'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode(data));
  }

Following is the output of json.encode(data)

{
  "sales_representative": 1,
  "doctor": 1,
  "remark": "my remarks",
  "date": "2021-12-05",
  "medicines": [
    {
      "medicine": 1,
      "quantity_type": "Tablet",
      "quantity": 5
    },
    {
      "medicine": 1,
      "quantity_type": "Tablet",
      "quantity": 5
    }
  ]
}
  • Related