使用flutter_osm获取当前位置时遇void类型赋值错误求助
解决flutter_osm获取当前位置的赋值报错问题
问题原因
你遇到的报错“This expression has a type of 'void' so its value can't be used”,是因为mapController.currentLocation()方法的返回类型是Future<void>——它的作用只是将地图相机移动到用户当前位置,不会返回任何地理位置数据,所以无法把它的结果赋值给GeoPoint变量。
解决方案
flutter_osm中,要获取当前位置的GeoPoint对象,需要使用myLocation()方法,这个方法返回Future<GeoPoint>,可以直接用await接收结果。
修改后的核心代码:
// 替换原来出错的那一行 GeoPoint currentLocation = await mapController.myLocation();
完整的onPressed代码块:
onPressed: () async { try { GeoPoint currentLocation = await mapController.myLocation(); debugPrint( "Current Location: Latitude: ${currentLocation.latitude}, Longitude: ${currentLocation.longitude}"); await mapController.addMarker( markerPosition: currentLocation, markerIcon: MarkerIcon( iconWidget: markerIcon, ), ); setState(() { geoPoint.add(currentLocation); widgetStateList.add(destinationState); }); } catch (e) { debugPrint("Error getting current location: $e"); } },
补充说明
如果调用myLocation()后地图没有自动定位到当前位置,可以额外调用mapController.currentLocation()触发地图相机移动:
GeoPoint currentLocation = await mapController.myLocation(); await mapController.currentLocation(); // 移动地图到当前位置
内容的提问来源于stack exchange,提问作者ErfanManafi
相关产品推荐
相关产品推荐

