flutter http post“类型'int'不是类型转换中类型'String'的子类型" [英] flutter http post "type 'int' is not a subtype of type 'String' in type cast"
本文介绍了flutter http post“类型'int'不是类型转换中类型'String'的子类型"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一些数据发布到此结构的后端:
I am trying to post some data to my backend of this structure:
class Activity {
String id;
String employeeId;
String locationId;
String locationName;
DateTime startDateTime;
DateTime endDateTime;
int breakMinutes;
String actionId;
String actionType;
int startDeviceType;
int endDeviceType;
String comment;
factory Activity.fromJson(Map<String, dynamic> json) =>
_$ActivityFromJson(json);
Map<String, dynamic> toJson() => _$ActivityToJson(this);
}
我正在将此类转换为Map:
I am converting the class to a Map like this:
Map<String, dynamic> _$ActivityToJson(Activity instance) => <String, dynamic>{
'id': instance.id,
'employeeId': instance.employeeId,
'locationId': instance.locationId,
'locationName': instance.locationName,
'startDateTime': instance.startDateTime?.toIso8601String(),
'endDateTime': instance.endDateTime?.toIso8601String(),
'breakMinutes': instance.breakMinutes,
'actionId': instance.actionId,
'actionType': instance.actionType,
'startDeviceType': instance.startDeviceType,
'endDeviceType': instance.endDeviceType,
'comment': instance.comment,
};
...并发送以下信息:
... and sending with this lines:
Future<HttpError> updateAsync(Activity activity) async {
var url = '...';
...
var body = activity.toJson();
Response response = await http.post(
url,
headers: headers,
body: body,
);
if (isSuccess(response.statusCode)) {
return null;
}
return new HttpError(
errorCode: response.statusCode, errorMessage: response.reasonPhrase);
}
...然后后端希望接收这些数据:
... Then the backend wants to receive those data:
{
"startDateTime": "2019-10-12T19:59:22.801Z",
"endDateTime": "2019-10-12T19:59:22.801Z",
"breakMinutes": 0,
"actionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"startDeviceType": 0,
"endDeviceType": 0,
"comment": "string"
}
我现在面临的问题是调用post()时出现错误
The problem I am facing now is that I get an error when calling post()
type 'int' is not a subtype of type 'String' in type cast
如果在转换为Map时对整数值调用.toString()
,则会得到415 - Unsupported Media Type
.
If I call .toString()
on the integer values when casting to a Map, I get 415 - Unsupported Media Type
.
那么这是一个错误,还是我在这里真的做错了什么?
So is this a bug or do I really do something wrong here?
推荐答案
更改
var body = activity.toJson(); // here body is still a Map<String, dynamic>
到
var body = json.encode(activity.toJson()); // here it's a JSON encoded string
这篇关于flutter http post“类型'int'不是类型转换中类型'String'的子类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文