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

Flutter中如何将List<dynamic>正确转换为List<LatLng>

出现这个问题的核心原因是Dart的map迭代方法没有拿到明确的泛型类型提示,当你处理的源数据是List<dynamic>时,默认会返回Iterable<dynamic>,最终toList()生成的自然是List<dynamic>,哪怕内部元素全是LatLng实例,类型系统也不会自动做收敛。

最稳妥的类型安全写法是给map显式指定泛型参数,在编译期就确定返回类型:

var latLngCoordinates = coordinates
  .map<LatLng>((coord) => LatLng(coord[0], coord[1]))
  .toList();

执行完这段代码后,latLngCoordinates的类型就会是标准的List<LatLng>,没有额外运行时转换开销。

如果你的源数据里坐标值是num类型(可能出现int、double混存的情况),可以在传参时加个简单的类型断言,避免构造函数参数类型报错:

var latLngCoordinates = coordinates
  .map<LatLng>((coord) => LatLng(coord[0] as double, coord[1] as double))
  .toList();

其他可选写法:

  • 调用toList()时用cast方法做类型转换:
    List<LatLng> latLngCoordinates = coordinates
      .map((coord) => LatLng(coord[0], coord[1]))
      .toList()
      .cast<LatLng>();
    

注意:不要直接用as List<LatLng>对结果做硬类型转换,这种写法不会校验列表内的元素类型,一旦类型不符合预期会直接抛出运行时崩溃,优先选择给map指定泛型的实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 01:03:32