Flutter传递双列表至新页面遇类型不匹配错误,求解决方案
解决
type 'List<Location>' is not a subtype of type 'Location' 错误 问题根源
locationFromAddress方法的返回值是List<Location>类型(哪怕只匹配到一个地址,也会返回包含单个元素的列表)- 你在
getCoordinates中直接将这个列表添加到location数组,导致location的元素类型变成了List<Location>,而非单个Location对象 - 跳转页面时传递的
location[index]是一个列表,但PlaceInfo组件要求接收单个Location,因此触发类型不匹配错误
修复步骤
修正地理编码结果的存储逻辑
从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}'); } } }确认数组声明类型正确
确保location变量的声明为单个Location的列表:List<Location> location = [];(可选)增加跳转前的安全校验
避免因索引越界或空值导致的额外错误: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
相关产品推荐
相关产品推荐

