[英]Latitude and Longitude is getting null in Flutter (Get Current Location)
I am using this plugin flutter_geofence
to get current location latitude and longitude.我正在使用这个插件
flutter_geofence
来获取当前位置的纬度和经度。 Below is the sample dart code, problem i facing is inside the Geofence
body i can get latitude and longitude but when i try to access outside it is getting null.下面是示例飞镖代码,我面临的问题是在
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'))),
),
);
DataService.class
数据服务类
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
}
}
This problem happend because your variables are outside the function (Geofence.getCurrentLocation().then ...), if you put this variables inside {} probably you can get different value than null, but I recommend create a new function outside the build method.发生此问题是因为您的变量在函数之外 (Geofence.getCurrentLocation().then ...),如果您将此变量放在 {} 内,您可能会获得与 null 不同的值,但我建议在构建之外创建一个新函数方法。
I recommend you use a state management like bloc or provider instead of setState.我建议你使用像 bloc 或 provider 这样的状态管理而不是 setState。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.