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

在Flutter中如何通过http库发送包含嵌套JSON结构的POST请求?

问题原因

你遇到的报错中文翻译为:未处理的异常:类型“List<Map<String, dynamic>>”不是类型转换中“String”类型的子类型
报错根本原因是:Flutter http库的post方法默认只会处理单层结构的Map参数,自动将其转为x-www-form-urlencoded格式的表单数据,无法处理嵌套的List、Map结构,遇到嵌套类型时就会触发类型转换失败。

修复方案
  • 首先导入内置的dart:convert库用于JSON序列化
  • 修改请求方法,手动将请求体序列化为JSON字符串,同时添加application/json请求头,告知后端接收的是JSON格式数据

修改后的请求方法代码如下:

import 'dart:convert';
import 'package:http/http.dart' as http;

static Future<http.Response> postSale(Map<String, dynamic> body) {
    return http.post(
        Uri.parse('http://192.168.56.1:8000/api/sales/'),
        // 必须设置JSON请求头
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        // 将整个Map序列化为JSON字符串
        body: jsonEncode(body),
    );
}
  • 调用时直接传入你构造的嵌套Map结构即可,示例如下:
// 构造请求体
Map<String, dynamic> reqBody = {
  "sales_representative": 1,
  "doctor": 1,
  "remark": "My Remark",
  "date": "2021-12-05",
  "medicines": [
    {
      "medicine": 1,
      "quantity_type": "Tablet",
      "quantity": 55
    },
    {
      "medicine": 1,
      "quantity_type": "Tablet",
      "quantity": 5
    }
  ]
};

// 发起请求
var res = await postSale(reqBody);
// 后续可处理返回结果,比如jsonDecode(res.body)解析返回的JSON
补充说明

如果你的后端原本配置为接收form-data格式的请求,嵌套结构不建议用form-data传输,调整后端接口适配JSON格式是兼容性最好的处理方案,也能避免很多参数解析异常。

内容的提问来源于stack exchange,提问作者Dhia Shalabi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:24:02