flutter 拒绝访问设备位置的权限

idv4meu8  于 2022-12-24  发布在  Flutter
关注(0)|答案(1)|浏览(263)
Position? position;
List<Placemark>? placeMarks;

getCurrentLocation() async
  {
    Position newPosition = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high, //exact location use high
    );
    position = newPosition; //get longitude and latitude
    placeMarks = await placemarkFromCoordinates(
        position!.latitude,
        position!.longitude,
    );
    Placemark pMark = placeMarks![0];
    String completeAddress = '${pMark.subThoroughfare} ${pMark.thoroughfare}, '
        '${pMark.subLocality} ${pMark.locality}, ${pMark.subAdministrativeArea}, '
        '${pMark.administrativeArea} ${pMark.postalCode}, ${pMark.country}'; 
    location.text = completeAddress;
  }

child: ElevatedButton.icon(
                          onPressed: (){
                            getCurrentLocation();
                          },
                          icon: const Icon(
                            Icons.location_on,

我没有在我的Android Studio错误,但当我点击按钮获取当前位置,它没有出现我的当前位置.

h7appiyu

h7appiyu1#

您还需要向用户请求位置权限,permission_handler包允许您使用系统对话框来请求权限:

if (await Permission.locationWhenInUse.request().isGranted) {
  // Either the permission was already granted before or the user just granted it.
}

如果权限已经被授予,它将不会再次询问用户,但会返回true。它还允许您检查位置是否打开:

if (await Permission.locationWhenInUse.serviceStatus.isEnabled) {
  // Use location.
}

在请求locationAlways之前,必须先请求locationWhenInUse权限。
(All示例改编自程序包README。)

相关问题