dart 我的当前位置不在控制台上显示

qxgroojn  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(140)

here's a screenshot of the code
代码运行良好之前,我目前的位置是打印在控制台上,然后我终止了程序,并再次运行它,然后它只是停止工作

e4eetjau

e4eetjau1#

首先,您需要在功能块之外释放位置变量,以便能够在构建小部件中访问它。

class _LoadingScreenState extends State<LoadingScreen> {
    late Position position;
// ...

接下来,需要使用setState更新位置状态;

// ...
    setState(() {
      position = await Geolocator.getCurrentPosition( /* complete the call here*/;
    });
    print(position);
    // ...

如需更多帮助或解释,请在下面发表评论。再见!

idv4meu8

idv4meu82#

官方文档是明确的和详细的.您可以参考这个链接geolocator,它显示了在获取当前位置的实现过程中要遵循的步骤.
1.首先,检查设备中是否启用了位置服务,
1.第二,检查并请求访问设备的位置的许可。
1.最后,在启用服务并授予权限时获取位置服务。
下面的代码,它是从官方文档复制:

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();
}

相关问题