1

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

2 Answers 2

2

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));
  }
Sign up to request clarification or add additional context in comments.

Comments

2

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
    }
  ]
}

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.