Flutter: Unhandled Exception: User denied permissions to access the device's location
Solution 1:
LocationPermission permission;
permission = await Geolocator.requestPermission();
request for the permission first by using this.
Solution 2:
class GeolocatorService {
Future<Position?> determinePosition() async {
LocationPermission permission;
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.deniedForever) {
return Future.error('Location Not Available');
}
} else {
throw Exception('Error');
}
return await Geolocator.getCurrentPosition();
}
}
Solution 3:
This is a common issues in geolocator that arises esp. when you don't grant permission to the device. By default it is disabled, so you have to request for it when the locatePosition()
is called. Remember that the geolocator package is wrapped under google_maps_flutter.
So to solve the location problem, ensure you do the following
class _MapScreenState extends State<MapScreen> {
void locatePosition() async {
bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();
await Geolocator.checkPermission();
await Geolocator.requestPermission();
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
currentPosition = position;
LatLng latLngPosition = LatLng(position.latitude, position.longitude);
// Ask permission from device
Future<void> requestPermission() async {
await Permission.location.request();
}
}