Flutter中Geolocator的getLocation无法获取lat、lon值问题
问题原因
当前代码无法正确获取经纬度的核心原因是getLocation()为异步无返回值方法,外部调用时不会等待定位、赋值逻辑执行完毕就会提前读取lat/lon属性,此时赋值操作尚未执行,就会出现值为null、late修饰变量报未初始化错误的问题。
修正代码
将getLocation()方法改为返回Future<void>类型,强制调用方等待异步逻辑执行完成后再读取属性值,同时补充定位服务、永久权限校验避免异常,完整代码如下:
import 'package:geolocator/geolocator.dart'; class Location { double? lat; double? lon; Future<void> getLocation() async { Position position = await _determinePosition(); lat = position.latitude; lon = position.longitude; } Future<Position> _determinePosition() async { // 校验定位服务是否开启 bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { return Future.error('Location service disabled'); } LocationPermission permission; permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { return Future.error('Permission Denied'); } } if (permission == LocationPermission.deniedForever) { return Future.error('Permission permanently denied'); } return await Geolocator.getCurrentPosition(); } }
调用规范
- 调用
getLocation()时必须使用await关键字等待执行完成,再读取经纬度值:
错误写法(必然读不到值):
Location location = Location(); location.getLocation(); // 未等待异步执行 print(location.lat); // 输出null正确写法:
Location location = Location(); await location.getLocation(); // 等待定位、赋值完成 print(location.lat); // 正常输出纬度值 print(location.lon); // 正常输出经度值
- 不建议使用
late关键字修饰lat/lon,一旦异步执行报错、或者调用方忘记await,就会直接抛出运行时崩溃,保留double?可空类型,读取前做非空判断兼容性更好。
内容的提问来源于stack exchange,提问作者Vipin
相关产品推荐
相关产品推荐

