readPosition method

Future<Position?> readPosition()

The current position, or null when it cannot be read.

Implementation

Future<Position?> readPosition() async {
  final List<(LocationAccuracy, Duration)> attempts =
      <(LocationAccuracy, Duration)>[
        (LocationAccuracy.high, preciseTimeout),
        (LocationAccuracy.medium, positionTimeout - preciseTimeout),
      ];
  final Stopwatch clock = Stopwatch()..start();
  for (final (LocationAccuracy accuracy, Duration limit) in attempts) {
    try {
      final Position position = await Geolocator.getCurrentPosition(
        locationSettings: LocationSettings(
          accuracy: accuracy,
          timeLimit: limit,
        ),
      );
      _noteFix(
        position,
        clock,
        accuracy == LocationAccuracy.high ? 'precise' : 'rough',
      );
      return position;
    } on TimeoutException {
      // On to the looser fix, then the last known one.
    } catch (e) {
      if (kDebugMode) debugPrint('Could not read position: $e');
      dev.log('location failed: $e');
      return null;
    }
  }

  try {
    final Position? last = await Geolocator.getLastKnownPosition();
    if (last != null && isRecent(last)) {
      _noteFix(last, clock, 'last known');
      return last;
    }
  } catch (e) {
    if (kDebugMode) debugPrint('Could not read last position: $e');
  }
  if (kDebugMode) debugPrint('No fix within $positionTimeout');
  dev.log(
    'location: none within ${positionTimeout.inSeconds}s, nor a recent one',
  );
  return null;
}