Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to post json body to php api in flutter?

I tried to post a JSON body to php api like this

var response = await http.post(
   Uri.parse("https://..."),
   body: {
     "orders": [
       {"id": 253, "userId": 13, "quantity": 2, "productId": 1},
       {"id": 257, "userId": 13, "quantity": 1, "productId": 3}
     ]
   });

and in the api I tried to access the variable like this

$data=$_POST["orders"];
echo $data[0]["id"];

but it always get the the error Undefined index
can anyone help me please? I’m a flutter newbie.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you are passing a raw data to your request then you have to encode that to json before passing. Try code below :

var response = await http.post(
   Uri.parse("https://..."),
   body: jsonEnocde(
       {
         "orders": [
       {"id": 253, "userId": 13, "quantity": 2, "productId": 1},
       {"id": 257, "userId": 13, "quantity": 1, "productId": 3}
     ]
   }
));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading