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

Flutter使用flutter_geofence取位置时经纬度在回调外为null如何解决

问题成因

该问题由Dart的异步执行逻辑导致:

  • Geofence.getCurrentLocation()是异步方法,返回Future对象,调用后不会阻塞后续代码执行,then内的回调需要等待定位请求完成才会触发
  • 你写的print语句是调用异步方法后同步执行的,此时定位请求还未返回结果,latitude和longitude尚未被赋值,因此输出为null
解决方案

推荐使用async/await语法简化异步逻辑,保证执行顺序符合预期:

1. 手势点击事件修改

onTap: () async {
  var latitude;
  var longitude;
  Geofence.initialize();
  Geofence.requestPermissions();
  // 等待异步定位方法执行完成再走后续逻辑
  var cd = await Geofence.getCurrentLocation();
  latitude = cd!.latitude;
  longitude = cd.longitude;
  // 此时变量已完成赋值,可正常访问
  print(latitude);
  print(longitude);
  // 其他需要使用经纬度的逻辑都写在await之后即可
}

2. DataService类方法修改

该方法本身已被async修饰,直接使用await等待定位结果即可:

class DataService {
  Future<List<RecommendedForYouData>?> makeRequestRecommendedForYou(
      BuildContext context) async {
    var latitude;
    var longitude;
    Geofence.initialize();
    Geofence.requestPermissions();
    // 等待定位结果返回
    var cd = await Geofence.getCurrentLocation();
    latitude = cd!.latitude;
    longitude = cd.longitude;
    print(latitude);
    print(longitude);
    // 后续使用经纬度发起接口请求的逻辑写在这里即可
  }
}

可选兼容方案

如果要保留then写法,需要把所有需要用到经纬度的逻辑都放到then回调内部,不要在回调外部访问变量:

Geofence.getCurrentLocation().then((cd) {
  latitude = cd!.latitude;
  longitude = cd.longitude;
  // 所有用到经纬度的逻辑都放在回调内部执行
  print(latitude);
  print(longitude);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:24:06