【问题标题】:Can't get user location after permission granted授予权限后无法获取用户位置
【发布时间】:2021-03-22 13:26:04
【问题描述】:

我尝试使用 Flutter location 包单击按钮时获取用户位置

代码

FloatingActionButton(
  onPressed: () async {
    await location
        .hasPermission()
        .then((PermissionStatus status) async {
      if (_permissionGranted == PermissionStatus.denied) {
        await location.requestPermission().then(
          (PermissionStatus requestStatus) async {
            print("PERMISSION TAKEN");
            await location
                .getLocation()
                .then((LocationData userLocation) {
              print("LOCATION TAKEN 1");
              print(userLocation);
            });
          },
        );
      } else {
        await location
            .getLocation()
            .then((LocationData userLocation) {
          print("LOCATION TAKEN 2");
          print(userLocation);
        });
      }
    });
  },
  child: Icon(Icons.place, color: Colors.white),
  backgroundColor: Colors.green,
),

当用户单击按钮请求位置权限时,在我的代码中授予权限后工作我的代码的这部分

print("PERMISSION TAKEN");

但是这部分代码不能工作

await location
    .getLocation()
    .then((LocationData userLocation) {
  print("LOCATION TAKEN 1");
  print(userLocation);
});

【问题讨论】:

  • 您在什么平台上测试 ios 或 android ? iOS 模拟器中目前存在一个错误,您必须手动选择多个位置才能让模拟器实际发送数据。在 iOS 模拟器中测试时请记住这一点。

标签: flutter dart flutter-dependencies


【解决方案1】:

我得到当前位置如下,尝试像这样使用

Future<LatLng> getUserLocation() async {
 LocationData currentLocation;

var location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
LocationData _locationData;

_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
  _serviceEnabled = await location.requestService();
  if (!_serviceEnabled) {
  }
}

_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.DENIED) {
  _permissionGranted = await location.requestPermission();
  if (_permissionGranted != PermissionStatus.GRANTED) {
  }
}

  // Platform messages may fail, so we use a try/catch PlatformException.
try {
  currentLocation = await location.getLocation();
  final lat = currentLocation.latitude;
  final lng = currentLocation.longitude;
  final coordinates = new Coordinates(lat, lng);
  var addresses =
      await Geocoder.local.findAddressesFromCoordinates(coordinates);

  var first = addresses.first;
  updateLocation(lat, lng, first.postalCode, first.locality,
      first.countryName, first.adminArea, first.addressLine);

  final center = LatLng(lat, lng);

  return center;
} on PlatformException catch (e) {
  if (e.code == 'PERMISSION_DENIED') {
    showToast("LOCATION PERMISSION DENIED",
        gravity: Toast.TOP, duration: Toast.LENGTH_LONG);
  }
  currentLocation = null;
}
}

别忘了在 Info.plist 中添加这个权限

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

【讨论】:

  • 您在单击按钮时调用此函数或在哪里调用此函数? @manpreet singh pandher
  • 就我而言,我在 initState 方法中调用此方法
【解决方案2】:

您也可以通过以下方式获取位置:---------

依赖项下的pubspec.yaml文件:----

dependencies:
 location: ^3.0.0

Android,在 AndroidManifest.xml 中添加此权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

iOS,你必须在 Info.plist 中添加这个权限:

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

警告:目前 iOS 模拟器中存在一个错误,您必须手动选择多个位置才能让模拟器实际发送数据。在 iOS 模拟器中测试时请牢记这一点。

main.dart

import 'package:flutter/material.dart';
import 'package:location/location.dart';

void main() => runApp(MyApp());

 class MyApp extends StatelessWidget {
 // This widget is the root of your application.
 @override
Widget build(BuildContext context) {
return MaterialApp(
  title: 'Flutter GPS',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: GetLocationPage(),
);
}
}

class GetLocationPage extends StatefulWidget {
 @override
_GetLocationPageState createState() => _GetLocationPageState();
}

 class _GetLocationPageState extends State<GetLocationPage> {
  LocationData _currentLocation;
  Location _locationService = new Location();

  @override
  void initState() {
// TODO: implement initState
super.initState();

_getLocation().then((value) {
  setState(() {
    _currentLocation = value;
  });
});
 }

    @override
   Widget build(BuildContext context) {
   return Scaffold(
  appBar: AppBar(),
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _currentLocation == null
            ? CircularProgressIndicator()
            : Text("Location:" +
                _currentLocation.latitude.toString() +
                " " +
                _currentLocation.longitude.toString()),
     

      ],
    ),
  ),
);
 }

  Future<LocationData> _getLocation() async {
   LocationData currentLocation;
try {
  currentLocation = await _locationService.getLocation();
} catch (e) {
  currentLocation = null;
}
return currentLocation;
 }
}

ss:---

为了请求位置,您应该始终手动检查位置服务状态和权限状态。参考这个https://pub.dev/packages/location

【讨论】:

  • 由于没有权限请求代码,您是如何获得位置权限的?
  • 这条线在&lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;没有任何权限请求代码@FaiiziiAwan
  • 我需要在不点击您的Get location 按钮的情况下获取用户位置。如果我允许访问位置,那么您的应用状态将为 loading@Wini
  • @Wini 更新版本的答案无法获取/显示用户位置。你可以看到here your code result
  • @AndreasHunter 我已经使用真实设备实现了这段代码你使用的是真实设备还是模拟器?
猜你喜欢
  • 2021-01-22
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多