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

Flutter中如何在请求参数中传递Map?模型参数合并报错解决

问题解决:Dart中合并两个Map<String,String>时的类型错误

错误原因

你在调用addAll时犯了两个关键错误:

  • 错误地将toJson()返回的Map用大括号{}包裹,导致创建了类型为Map<Map<String,String>, dynamic>的新Map,而非直接使用目标Map。
  • 强行用as Map<String, String>进行类型转换,这种转换不符合Dart类型系统,必然抛出类型转换异常。

修复后的代码

修正后的请求方法

@override
Future<List<MainModel>> get({
  FilterStationParamsModel? filterStationParamsModel,
}) async {
  final apiKeyMap = await ApiKey.getCryptoApiKeyMap();
  
  // 先判断参数非空,再合并Map
  if (filterStationParamsModel != null) {
    apiKeyMap?.addAll(filterStationParamsModel.toJson());
  }

  const String url = '/user';
  final response = await _helper.get(url: url, queryParameters: apiKeyMap);

  final data = jsonDecode(response.body)['data'] as List;
  return data
      .map((json) => MainModel.fromJson(json))
      .toList();
}

额外优化:FilterStationParamsModel的toJson方法

当前toJson方法固定返回字符串'123123',建议改成使用模型自身属性值,贴合实际业务需求:

Map<String, String> toJson() {
  return {
    if (limit != null) 'limit': limit.toString(),
    if (offset != null) 'offset': offset.toString(),
  };
}

关键说明

  • addAll方法接受的参数就是Map<String, String>类型,filterStationParamsModel.toJson()已直接返回该类型,无需额外包装或转换。
  • 增加空安全判断,避免filterStationParamsModel为null时触发空指针异常,提升代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:40:45