flutter - 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
}
}
解决方案
发生此问题是因为您的变量在函数之外(Geofence.getCurrentLocation().then ...),如果您将此变量放在 {} 内,您可能会获得与 null 不同的值,但我建议在构建之外创建一个新函数方法。
- 如果您使用有状态小部件:
- 在类的顶部声明你的变量。
- 使用 initState 并在内部调用您的方法(Geofence.initialize()、Geofence.requestPermissions()、Geofence.getCurrentLocation())
- 您可以在 initState 之外创建一个特定函数以在您的构建方法内部调用。
- 在您的特定函数中,您需要调用 setState 函数来重建您的 UI。
我建议您使用 bloc 或 provider 之类的状态管理,而不是 setState。
推荐阅读
- rspec - 找不到未禁用的字段
- linux - 如果命令在 X 秒内为真,则在 bash shell 脚本中运行代码
- c# - 如何获取对象的键作为键值对?
- blender - 如何处理 3D 打印的非流形顶点
- c# - 我应该为机器人使用哪个身份验证提供程序?
- c# - 有没有办法可以减少启动/停止秒表和测量毫秒所需的代码?
- node.js - 错误 [ERR_HTTP_HEADERS_SENT] 发送到客户端后无法设置标头
- ios - 是否可以将 Apple 的 Face ID 技术用于应用程序
- c++ - 从父类的相同方法调用派生类方法
- node.js - 如何配置 node-fetch 以使用公司代理?