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

Flutter报错:_InternalLinkedHashMap<String,dynamic>非String子类型问题

解决Flutter中_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String')报错

问题根源

你这段代码的报错核心在于重复解析JSON:

  • getReverseGeocodingGivenLatLngUsingMapbox方法里,Dio发起GET请求后,responseData.data已经自动把JSON响应解析成了Map<String, dynamic>类型(因为你配置了JSON的contentType,Dio默认会做这个解析)
  • 但在getParsedReverseGeocoding里,你又调用json.decode()去处理这个已经解析好的Map,相当于把Map对象当成String传进去,自然触发类型不匹配错误

修改后的正确代码

Future<Map> getParsedReverseGeocoding(LatLng latLng) async {
  // 直接使用返回的Map,无需再json.decode
  var response = await getReverseGeocodingGivenLatLngUsingMapbox(latLng);
  Map feature = response['features'][0];
  Map revGeocode = {
    'name': feature['text'],
    'address': feature['place_name'].split('${feature['text']}, ')[1],
    'place': feature['place_name'],
    'location': latLng
  };
  return revGeocode;
}

// 建议指定返回类型,增强代码安全性
Future<Map<String, dynamic>?> getReverseGeocodingGivenLatLngUsingMapbox(LatLng latLng) async {
  String query = '${latLng.longitude},${latLng.latitude}';
  String url = '$baseUrl/$query.json?access_token=$accessToken';
  url = Uri.parse(url).toString();
  print(url);
  try {
    _dio.options.contentType = Headers.jsonContentType;
    final responseData = await _dio.get(url);
    return responseData.data;
  } catch (e) {
    final errorMessage = DioExceptions.fromDioError(e as DioError).toString();
    debugPrint(errorMessage);
    // 出错时返回null,避免后续调用报错
    return null;
  }
}

额外提示

  • Dio处理JSON响应时,默认会自动解析成Map或List,不需要手动调用json.decode()
  • 给异步方法指定明确的返回类型,能提前发现类型问题,避免运行时错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:45:39