flutter http post“类型'int'不是类型转换中类型'String'的子类型”

时间:2019-10-12 20:32:47

标签: rest http post flutter dart

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

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:

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,
    };

...并发送以下行:

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);
  }


...然后后端希望接收这些数据:

{
  "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

这是一个错误还是我在这里真的做错了什么?

1 个答案:

答案 0 :(得分:1)

更改

  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