You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter/Dart调用Rest API保存数据时遇类型不匹配错误

类型不匹配异常原因及解决办法

原因分析

异常Error: Expected a value of type 'String', but got one of type 'int'的核心原因是HTTP请求的body格式处理错误:

  • 使用http.post并直接传入Map类型的body时,Flutter的http库默认会按application/x-www-form-urlencoded(表单)格式编码,这种格式要求所有参数值必须是字符串类型。
  • 你的LancamentosModel.toJson()方法返回的Map中包含多个int类型字段(如id、valor、idTPRD等),这些int值直接传入会触发类型校验失败。

解决办法

有两种可行的修复方案,推荐使用第二种(JSON格式请求),更符合API交互的常规做法:

方案1:将所有int字段转为字符串后传表单格式

修改toJson()方法,把所有int类型的字段转为字符串:

Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = new Map<String, dynamic>();
  data['id'] = this.id?.toString();
  data['obs'] = this.obs;
  data['dataVcto'] = this.dataVcto;
  data['valor'] = this.valor?.toString();
  data['idTPRD'] = this.idTPRD?.toString();
  data['dataLcto'] = this.dataLcto;
  data['status'] = this.status;
  data['idUSRS'] = this.idUSRS?.toString();
  data['dC'] = this.dC;
  data['idCTCT'] = this.idCTCT?.toString();
  data['tPRD_Nome'] = this.tPRDNome;
  data['uSRS_Nome'] = this.uSRSNome;
  data['cTCT_Nome'] = this.cTCTNome;
  return data;
}

方案2:发送JSON格式的请求(推荐)

将请求body编码为JSON字符串,并设置正确的Content-Type头,后端可直接解析JSON数据,无需转换字段类型:

  1. 修改salvarDados方法:
import 'dart:convert'; // 需导入该包

Future salvarDados(LancamentosModel dados) async {
  var resp = await http.post(
    Uri.parse("http://hjsystems.dynns.com:8085/GravaLancamentos"),
    headers: {
      "Authorization": "Basic *******************",
      "Content-Type": "application/json" // 添加JSON格式标识头
    },
    body: jsonEncode(dados.toJson()) // 将Map转为JSON字符串
  );
  if (resp.statusCode != 200) throw Exception("Erro ao salvar");
}

额外检查点:

  • status: _controller.toString():如果_controller是下拉选择类控件,建议直接获取选中的字符串值,避免不必要的toString()导致格式问题。

内容的提问来源于stack exchange,提问作者Felippe Pinheiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 13:05:19