determinePosition function
Future<Position>
determinePosition(
)
Implementation
Future<Position> determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error(localizedText('Location services are disabled.'));
}
// First check the current permission status
permission = await Geolocator.checkPermission();
// If we're on Android and permission isn't granted yet, show our disclosure first
if (Platform.isAndroid &&
(permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) &&
!_hasShownLocationDialog) {
_hasShownLocationDialog = true;
bool hasAgreed = await showLocationDisclosureDialogAfterFrame();
if (!hasAgreed) {
return Future.error(
localizedText('User did not agree to location data disclosure.'));
}
// Only after user agrees to our disclosure, request system permission
permission = await Geolocator.requestPermission();
} else if (Platform.isIOS && (permission == LocationPermission.denied)) {
// For non-Android platforms or if dialog was already shown
permission = await Geolocator.requestPermission();
}
// Check the result of the permission request
if (permission == LocationPermission.denied) {
return Future.error(localizedText('Location permissions are denied'));
}
if (permission == LocationPermission.deniedForever) {
return Future.error(localizedText(
'Location permissions are permanently denied, we cannot request permissions.'));
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
Position? lastKnownPosition = await Geolocator.getLastKnownPosition();
if (lastKnownPosition != null) {
Duration difference =
DateTime.now().difference(lastKnownPosition.timestamp);
if (difference.inMinutes < 1) {
return lastKnownPosition;
}
}
showSnackbarForFetchingLocation();
var pos = await Geolocator.getCurrentPosition();
_showingMessageForFetchingLocation = false;
return pos;
}