getCurrentLocation method
Retrieves the user's current GPS position.
This method:
- Checks whether location services are enabled.
- Verifies and requests permissions if necessary.
- Returns a Position with high accuracy.
Throws:
- LocationServicesDisabledException if location services are turned off.
- LocationPermissionDeniedException if the user denies the permission request.
- LocationPermissionPermanentlyDeniedException if permission is permanently denied.
Example:
final position = await GeolocatorService().getCurrentLocation();
Implementation
Future<Position> getCurrentLocation() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) throw LocationServicesDisabledException();
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
throw LocationPermissionDeniedException();
}
}
if (permission == LocationPermission.deniedForever) {
throw LocationPermissionPermanentlyDeniedException();
}
return await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(accuracy: LocationAccuracy.best),
);
}