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

Flutter如何在POST接口请求中发送指定格式的数组?现有代码问题求助

存在的问题

  • 发送请求时仅读取了sent数组的第一个元素sent[0],没有遍历所有选中的选项,因此只能提交单条数据
  • 已定义的Sent、Data数据模型没有被使用,没有利用模型自带的toJson()能力自动生成符合要求的嵌套结构
  • sent声明为List<dynamic>,没有明确类型,容易出现运行时类型转换错误

修复代码

第一步:优化变量声明(可选,推荐)

将原来的List<dynamic> sent;改为明确类型,适配空安全:

List<List<int>>? sent;

第二步:修改saveAnswer方法

Future<Sent?> saveAnswer() async {
  // 判空处理,避免无选项选中时报错
  if (sent == null || sent!.isEmpty) {
    print("未选中任何选项");
    return null;
  }
  // 遍历所有选中条目,转换为Data模型列表
  List<Data> dataList = sent!.map((item) {
    return Data(
      questionId: item[0],
      optionId: item[1],
    );
  }).toList();
  // 组装成接口要求的外层结构
  Sent requestBody = Sent(data: dataList);

  var url = await Network().link("/exercise/1/saveAnswer");
  SharedPreferences localStorage = await SharedPreferences.getInstance();
  final token = jsonDecode(localStorage.getString('token'));
  http.Response response = await http.post(
    Uri.parse(url),
    // 直接序列化模型,自动生成符合要求的JSON结构
    body: jsonEncode(requestBody.toJson()),
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    }
  );
  if (response.statusCode == 200) {
    print("提交成功:${response.body}");
    return Sent.fromJson(jsonDecode(response.body));
  } else {
    print("提交失败:${response.body}");
    return null;
  }
}

修改后发送的请求结构就会完全匹配你要求的格式:外层包裹data字段,内部是所有选中答案的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:36:00