Emmanuel
Emmanuel

Reputation: 345

How do I handle a future not returning?

I'm using a location plugin to get the current location of the device. However, on certain devices, await getLocation() never returns (there are also no errors in the debug console). How do I handle such an issue?

this is my code for getCurrentLocation()

import 'package:geolocator/geolocator.dart';
import 'location.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> getCurrentLocation() async {
  bool serviceEnabled;
  LocationPermission permission;
  Position position;
  await reqLocation(); // requests turn on location
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.deniedForever) {
    return Future.error(
        'Location permissions are permantly denied, we cannot request permissions.');
  }

  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission != LocationPermission.whileInUse &&
        permission != LocationPermission.always) {
      return Future.error(
          'Location permissions are denied (actual value: $permission).');
    }
  }
  print('LOGIC');
  position = await Geolocator.getCurrentPosition();
  if (position == null) {
    print('null');
  } else {
    print('LOCATION');
    print(position);
  }
  return position;
}

Upvotes: 1

Views: 956

Answers (1)

Afridi Kayal
Afridi Kayal

Reputation: 2285

Use a timeout for your future to handle this case: Flutter - Future Timeout

Use your future like this:

var result = await getCurrentLocation().timeout(const Duration(seconds: 5, onTimeout: () => null));

Now, your future runs for 5 seconds and if the operation is not complete yet, the future completes with null (because onTimeout returned null. You can use a different value as you like [Refer to the link above]).

Now check result. if null, the operation did not complete within specified time limit else you get your position value in result as usual if it managed to complete within the specified duration.

Upvotes: 6

Related Questions