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

Flutter传递双列表至新页面遇类型不匹配错误,求解决方案

解决 type 'List<Location>' is not a subtype of type 'Location' 错误

问题根源

  • locationFromAddress 方法的返回值是 List<Location> 类型(哪怕只匹配到一个地址,也会返回包含单个元素的列表)
  • 你在 getCoordinates 中直接将这个列表添加到 location 数组,导致 location 的元素类型变成了 List<Location>,而非单个 Location 对象
  • 跳转页面时传递的 location[index] 是一个列表,但 PlaceInfo 组件要求接收单个 Location,因此触发类型不匹配错误

修复步骤

  1. 修正地理编码结果的存储逻辑
    从 locationFromAddress 返回的列表中提取单个 Location 对象,再添加到数组中,同时增加非空判断避免异常:

    Future<void> getCoordinates() async {
      for (int i = 1; i < destination.length; i++) {
        final List<Location> coords = await locationFromAddress('${destination.elementAt(i).destination}');
        if (coords.isNotEmpty) {
          location.add(coords.first);
          print('$i ${location.last}');
        }
      }
    }
    
  2. 确认数组声明类型正确
    确保 location 变量的声明为单个 Location 的列表:

    List<Location> location = [];
    
  3. (可选)增加跳转前的安全校验
    避免因索引越界或空值导致的额外错误:

    return GestureDetector(
      onTap: () {
        if (index < location.length && location[index] != null) {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => PlaceInfo(
              packageModel: destination[index], 
              location: location[index]
            )),
          );
        }
      },
    );
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:10:20