首页 > 解决方案 > Flutter 中的纬度和经度为空(获取当前位置)

问题描述

我正在使用这个插件flutter_geofence来获取当前位置的纬度和经度。下面是示例飞镖代码,我面临的问题是在Geofence身体内部我可以获得纬度和经度但是当我尝试在外部访问时它变得空。

return Scaffold(
          body: Container(
            child: GestureDetector(
                onTap: () {
                  var latitude;
                  var longitude;
                  Geofence.initialize();
                  Geofence.requestPermissions();
                  Geofence.getCurrentLocation().then((cd) {
                    latitude = cd!.latitude;
                    longitude = cd.longitude;
                  });
                  print(latitude); // getting null
                  print(longitude); // getting null
                },
                child: Center(child: Text('Test'))),
          ),
        );

数据服务类

class DataService {
Future<List<RecommendedForYouData>?> makeRequestRecommendedForYou(
      BuildContext context) async {
var latitude;
var longitude;
Geofence.initialize();
                  Geofence.requestPermissions();
                  Geofence.getCurrentLocation().then((cd) {
                    latitude = cd!.latitude;
                    longitude = cd.longitude;
                  });
                  print(latitude); // getting null
                  print(longitude); // getting null
}
}

标签: flutterdart

解决方案


发生此问题是因为您的变量在函数之外(Geofence.getCurrentLocation().then ...),如果您将此变量放在 {} 内,您可能会获得与 null 不同的值,但我建议在构建之外创建一个新函数方法。

  1. 如果您使用有状态小部件:
  • 在类的顶部声明你的变量。
  • 使用 initState 并在内部调用您的方法(Geofence.initialize()、Geofence.requestPermissions()、Geofence.getCurrentLocation())
  • 您可以在 initState 之外创建一个特定函数以在您的构建方法内部调用。
  • 在您的特定函数中,您需要调用 setState 函数来重建您的 UI。

我建议您使用 bloc 或 provider 之类的状态管理,而不是 setState。


推荐阅读