首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >flutter http post "type 'int‘is not a subtype of type 'String’in type cast“

flutter http post "type 'int‘is not a subtype of type 'String’in type cast“
EN

Stack Overflow用户
提问于 2019-10-13 04:32:47
回答 1查看 1.1K关注 0票数 1

我正在尝试将一些数据发布到此结构的后端:

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
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,
    };

..。并使用此行发送:

代码语言:javascript
复制
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);
  }

..。然后后端想要接收这些数据:

代码语言:javascript
复制
{
  "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()时出现错误

type 'int' is not a subtype of type 'String' in type cast

如果在转换为Map时对整数值调用.toString(),则会得到415 - Unsupported Media Type

那么,这是一个bug,还是我真的做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-13 06:00:46

变化

代码语言:javascript
复制
  var body = activity.toJson(); // here body is still a Map<String, dynamic>

代码语言:javascript
复制
  var body = json.encode(activity.toJson()); // here it's a JSON encoded string
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58358234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档