How To Post Int/integer Value As Json From Dart/flutter
I am using asp.net core web API as back-end. There is a method that accepts a single integer value. Method([FromBody] int value) I want to post the integer value from dart/flutter
Solution 1:
Please refer my code
import
import'package:http/http.dart'as http;
http request
var client = new http.Client(); client.post(Uri.encodeFull("Your url"), body: { "param1": "value1", "param2": 11, // integer value type }).then((response) { client.close(); if (this.mounted && response.statusCode == 200) { //enter your code for change state } }).catchError((onError) { client.close(); print("Error: $onError"); });
I hope it will help you.
PS:
var client = new http.Client();
var response = await client.post(Uri.encodeFull("Your Url"), body : "0", header : {/*Your headers*/"});
Solution 2:
You can try this code.
Http.post(url, body:{"id": "0"},headers:{"content-type":"application/json"}
Solution 3:
I had the same problem when trying to send an HTTP request to an API that has an integer as one of its arguments(age). Dart wanted me to convert the int into a string and the API was not accepting the int as a string. Hence I was getting the same error and ended up in this question.
My solution was to store the input in a map, add a header {"content-type":"application/json"} and pass the map in the body arguement.
import'dart:convert';
import'package:http/http.dart'as http;
Future<String> register_user() async {
var req_body = newMap();
req_body['username'] = 'John Doe';
req_body['age'] = 20; /* The integer */
final response = await http.post(
'http://127.0.0.1:8081/user/register',
headers: {'Content-Type': 'application/json'},
body: jsonEncode(req_body));
if (response.statusCode == 200) {
varobject = json.decode(response.body);
returnobject.toString();
} elseif (response.statusCode == 422) {
return'Error';
} else {
return'Can not connect to server';
}
}
Solution 4:
Can you try bellow one
var queryParameters = {
'value': '0'
};
var uri =
Uri.https('www.myurl.com', '/api/sub_api_part/', queryParameters); //replace between part and your urlvar response = await http.get(uri, headers: {
HttpHeaders.contentTypeHeader: 'application/json'
});
Post a Comment for "How To Post Int/integer Value As Json From Dart/flutter"