1:使用 插件 geolocator ,官网 https://pub.dev/packages/geolocator

2:按照官网配置,代码照抄

static Future<FlutterLocation> determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;
    Position p;

    try {
    //这里使用的权限申请插件 ,请自行搜索相关文档配置获取依赖 PermissionStatus permissionStatus
= await LocationPermissions().requestPermissions(); if(PermissionStatus.granted == permissionStatus) { // 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.deniedForever) { // Permissions are denied forever, handle appropriately. return Future.error( 'Location permissions are permanently denied, we cannot request permissions.'); } 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'); } } // p = await AMapLocationClient.getLocation(true); p = await Geolocator.getCurrentPosition(); print('location is get ${p}'); } else{ await LocationPermissions().openAppSettings(); } } catch (e) { ToastUtil.showToast('获取定位失败:$e'); } return FlutterLocation(p?.latitude, p?.longitude); }

以上都是官网代码,只新增了申请权限的代码(其实加不加都一样,实列代码也可以申请权限)

然后自己封装了一下经纬度

class FlutterLocation {
  double lat;
  double lng;
  FlutterLocation(this.lat, this.lng);
}

正常情况下,大部分安卓手机调用这段代码都能正确获取手机定位,但是在部分机型上面,特别是华为手机上(我自己碰到的情况,不代表全部)不能正确获取到手机定位,网上搜索资料,权限申请也添加了,gps定位也打开了,死活不行。

后来查资料发现,安卓手机获取定位需要使用google服务来对gps返回信息进行解析,但是国内很多手机厂商都屏蔽了google服务,所有手机上即使获取到了定位权限,也不一定能获取到正确的定位,会一直阻塞在调用google服务上面,不报错也不返回(卡死在 determinePosition.then()这里,有时catcherror能返回)

那么这种情况有两种解决方案

1:使用百度、高德api 

2:对于定位精度要求不高的,可以使用web api的形式来获取,比如: https://apis.map.qq.com/ws/location/v1/ip (需要自己申请key)