i'm trying to send data to my server using post http method. Backend works perfectly (test made with postman) but i'm getting this error in flutter!
here is my code:
Future<MesureModel?> postMeasurement(String description) async {
final response = await http.post(
Uri.parse('${baseUrl}/api/v1/measurements/create'),
body: {"description": description});
var data = response.body;
return MesureModel.fromJson(jsonDecode(response.body));
}
and here is my model:
List<MesureModel> mesureModelFromJson(String str) => List<MesureModel>.from(
json.decode(str).map((x) => MesureModel.fromJson(x)));
String mesuretModelToJson(List<MesureModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class MesureModel {
MesureModel(
{required this.measurement_id,
required this.measured_value,
required this.taken_by,
required this.param_name,
required this.description});
int measurement_id;
double measured_value;
String taken_by;
String param_name;
String description;
factory MesureModel.fromJson(Map<String, dynamic> json) => MesureModel(
measurement_id: json["measurement_id"],
measured_value: json["measured_value"],
taken_by: json["taken_by"],
param_name: json["param_name"],
description: json["description"]);
Map<String, dynamic> toJson() => {
"measurement_id": measurement_id,
"measured_value": measured_value,
"taken_by": taken_by,
"param_name": param_name,
"description": description
};
}
I would be grateful if anyone could help me!
CodePudding user response:
Future<MesureModel?> postMeasurement(String description) async {
final response = await http.post(
Uri.parse('${baseUrl}/api/v1/measurements/create'),
headers: {
'Content-Type': 'application/json',
},
body: json.encode({"input_description": description}));
var data = response.body;
return MesureModel.fromJson(jsonDecode(response.body));
}
Json encode the body before sending
CodePudding user response:
You should specify Content-Type
and encode payload
final response = await http.post(
Uri.parse('${baseUrl}/api/v1/measurements/create'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
"description": description,
}),
);
var data = response.body;
return MesureModel.fromJson(jsonDecode(response.body));