Geolocator Plugin to get current location

2020-04-19 06:16发布

问题:

I am using Geolocator plugin to get the current location of the device, and google map plugin to integrate the map widget in the flutter

The google map works fine, but the Geolocator it gives me this error:

D/permissions_handler(10148): No permissions found in manifest for: $permission
D/permissions_handler(10148): No permissions found in manifest for: $permission

and the error still appears, any idea of why this happening?

And in the file Androidmanifest.xml I added these permissions inside

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

回答1:

The problem is google_maps_flutter package needs permission for accessing your location but the package has not native codes to ask that permission.

So you need to write native code or just install another package which is able to take that permission.

Install this: https://pub.dartlang.org/packages/location

Then:

getLocationPermission() async {
    final Location location = new Location();
    try {
      location.requestPermission(); //to lunch location permission popup
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        print('Permission denied');
      }
    }
  }

Or if you want more solid code, this is my code for some project(with location package):

//Show some loading indicator depends on this boolean variable
bool askingPermission = false;

@override
  void initState() {
    this.getLocationPermission();
    super.initState();
  }

  Future<bool> getLocationPermission() async {
    setState(() {
      this.askingPermission = true;
    });
    bool result;
    final Location location = Location();
    try {
      if (await location.hasPermission())
        result = true;
      else {
        result = await location.requestPermission();
      }
      print('getLocationPermission: '
          '${result ? 'Access Allowed' : 'Access Denied'}');
    } catch (log, trace) {
      result = false;
      print('getLocationPermission/log: $log');
      print('getLocationPermission/trace: $trace');
    } finally {
      setState(() {
        this.askingPermission = false;
      });
    }
    return result;
  }


回答2:

add this package into flutter project.. - pubspec.yaml

-dependencies:

  location: ^2.3.4