How to send a boolean value or an integer in http request body in dart? The documentation says that I can only send string, list or a Map. How to make it work for boolean or integer in Dart?
How to send a boolean value or an integer in http request body in dart? The documentation says that I can only send string, list or a Map. How to make it work for boolean or integer in Dart?
Try this approach which I use in my projects
void apiPost(){
var body = jsonEncode(
{
"string":"test",
"bool":true,
"int":1
});
http.post("url here",body: body,headers: {"Content-Type": "application/json"}).then((response) {
Map map = json.decode(response.body);
});
}
As you saw in the documentation, you can only send those three things: a byte array, a string or a map of string to string. In fact, in the end, you are just sending a byte array. The other options get converted to bytes before sending.
A string is converted to bytes by transforming it into bytes using utf-8 (or some other encoding specified by the content-type header).
A map of string to string is encoded to first as x-www-form-urlencoded and then to bytes. That encoding can, of course, only encode strings.
So the answer to your question really depends on where/how the server expects to receive the fields. If it's expecting them in a form, then it's your responsibility to convert, say, a boolean into whatever string the server expects. Maybe that's 'true'/'false' or '1'/'0' or something else. Make your map like this:
int someInt;
bool someBool;
var formData = <String, String>{
'an_int_value' : someInt.toString(),
'a_bool_value' : someBool.toString(), // assuming 'true'/'false' is OK
};
Also consider the possibility that your server requires a completely different encoding, like JSON. Then you would convert your map to JSON, then pass that as a string, setting the content-type appropriately.