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

Flutter Post API请求实现求助(附尝试代码)

Flutter Post API 请求代码问题排查与修正

问题分析

你当前的代码存在几个关键问题,导致无法正确发起符合要求的Post请求:

  • 请求格式不匹配:设置了Content-Type: application/json,但直接将File和自定义BuyerModel对象放入请求体,既无法序列化为JSON,也不符合文件上传的要求(文件上传需用multipart/form-data格式)。
  • 对象未序列化:BuyerModel是自定义对象,直接传入请求体无法被服务器解析,需要先转换为JSON字符串。
  • 异常处理不全面:未处理HTTP响应状态码(如4xx/5xx错误)、文件读取失败等场景,容易出现未知报错。

修正后的代码示例

class ProfileRemoteDatasourceImpl implements ProfileRemoteDatasource {
  @override
  Future<SaveBuyerModel> saveBuyerInfo({required File image, required BuyerModel buyerModel}) async {
    try {
      const endpoint = '${MyAppConstants.baseUrl}/v1/save/buyer';
      // 使用MultipartRequest处理文件上传和表单数据
      var request = http.MultipartRequest('POST', Uri.parse(endpoint));

      // 添加文件:参数名需与Postman中一致
      request.files.add(await http.MultipartFile.fromPath(
        'File',
        image.path,
      ));

      // 将BuyerModel序列化为JSON字符串后添加到表单字段
      request.fields['buyerModel'] = json.encode(buyerModel.toMap());

      // 发送请求并获取响应
      final response = await request.send();
      final responseBody = await response.stream.bytesToString();

      // 处理异常状态码
      if (response.statusCode >= 400) {
        throw ServerException('请求失败: ${response.statusCode}');
      }

      Map<String, dynamic> data1 = json.decode(responseBody)["data"];
      return SaveBuyerModel.fromMap(data1);
    } on ServerException catch (e) {
      throw ServerException(e.message);
    } on IOException catch (e) {
      throw ServerException('文件读取或网络错误: ${e.toString()}');
    } catch (e) {
      throw TimeoutException(e.toString());
    }
  }
}

关键注意事项

  • 确保BuyerModel实现了toMap()方法,能将对象转换为可序列化的Map结构,才能顺利转为JSON字符串。
  • 确认文件参数名(示例中为File)与Postman中设置的参数名完全一致,否则服务器无法识别上传的文件。
  • MultipartRequest会自动设置正确的Content-Type,无需手动指定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:17:35