下面是代码的截图
在控制台打印当前位置之前,代码运行得很好,然后我终止了程序并再次运行,然后它就停止工作了
首先,您需要在函数块之外声明您的位置变量,以便能够在构建Widgets中访问它。
class _LoadingScreenState extends State<LoadingScreen> {
late Position position;
// ...
接下来,您需要使用setState
;
// ...
setState(() {
position = await Geolocator.getCurrentPosition( /* complete the call here*/;
});
print(position);
// ...
如果需要更多的帮助或解释,请在下面评论。再见!
官方文档是明确和详细的。你可以参考这个链接地理定位器,它显示了在实现获取当前位置的过程中要遵循的步骤。
- 首先,检查设备是否启用了定位服务,
- 其次,检查并请求访问设备位置的权限。
- 最后,当服务启用时获取位置服务
下面的代码,它是从官方文档中复制的:
import 'package:geolocator/geolocator.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}