fluttergeolocator

Flutter package Geolocator not showing current location


I am learning Flutter and trying to rebuild Clima project following londonappbrewery's flutter course. After I installed the geolocator package and invoked the getCurrentPosition method, I got nothing.

The geolocator version is ^9.0.2 with flutter 3.10.6 and I'm testing on a physical device.

geolocator package problem

void getLocation() async {
    LocationPermission permission = await Geolocator.requestPermission();
    print(permission);
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
    print(position);
}

I manually asked permission from the device, but it's still not working.

This is what I add to the AndroidManifest.xml file:

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

Solution

  • You need to also check the Location Service status. Try this code:

    Future<Position> determinePosition() async {
      final serviceEnabled = await Geolocator.isLocationServiceEnabled();
    
      if (!serviceEnabled) {
        return Future.error('Location service is disabled.');
      }
    
      var permission = await Geolocator.checkPermission();
    
      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
        if (permission == LocationPermission.deniedForever) {
          return Future.error('Location permission is denied forever.');
        }
        if (permission == LocationPermission.denied) {
          return Future.error('Location permission is denied.');
        }
      }
    
      return Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.low,
      );
    }
    

    And change your permissions in AndroidManifest.xml to:

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

    With ACCESS_COARSE_LOCATION only it might take a long time (minutes) before you will get your first locations fix.

    If this doesn't help, check that all the rest plugin's requirements for Android are met.