I’ve recently started to use Flutter in order to develop Android apps.
Uselessly difficult and counter-intuitive, but I expected that having already developed under Android environment in the past (with Android Studio).
Anyway, I’m trying to make a simple POST request to a PHP page and retrieve the data.
The client-side is the following:
Future<User> createUser(String name, int id) async {
// perform await (asynchronous) of a POST request, passing data in the body
final response = await http.post(
Uri.parse('http://MY_SERVER/json-encode.php'),
headers: {"content-type": "application/json"},
body: json.encode({
'id' : id,
'name' : name
}),
);
// if the server returned 200 OK
if (response.statusCode == 200) {
// rest of the code
}
}
I call the method with a button
ElevatedButton(
onPressed: () {
createUser(_controller.text, 0);
},
child: const Text('Search user'),
),
The server-side (PHP page) is the following:
<?php
$data = array("id" => isset($_POST['id']) ? $_POST['id'] : -1, "name" => isset($_POST['name']) ? $_POST['name'] : 'NOT RECEIVED');
// return the same JSON data as confirmation,
// or fixed data if something was not received correctly
echo json_encode($data);
exit();
?>
the client receives the data back from the PHP page, but does not send POST data (i receive -1 as ID and ‘NOT RECEIVED’ as name)
I also tried to add
header("Content-Type: application/json");
in the PHP page, but nothing changes.
For what absurd reason this (should be) simple code does not work as intended?
Thanks.