getUserLocation function

Future<String> getUserLocation()

Implementation

Future<String> getUserLocation() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Check if location service is enabled
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    throw 'Location service is disabled.';
  }

  // Request location permission
  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.deniedForever) {
    throw 'Location permission is permanently denied, we cannot request permission.';
  }

  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission != LocationPermission.whileInUse &&
        permission != LocationPermission.always) {
      throw 'Location permissions are denied (actual value: $permission).';
    }
  }

  // Get the current position
  Position position = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.medium,
  );

  // Retrieve the address details
  List<Placemark> placemarks = await placemarkFromCoordinates(
    position.latitude,
    position.longitude,
  );

  // Extract city and country from the address
  Placemark placemark = placemarks.first;
  String city = placemark.locality ?? '';
  String country = placemark.country ?? '';

  return '$city, $country';
}