Sub topic 10
Getting the Current Position
This chapter assumes that you know basic Dart and Flutter widget syntax, can use async and await, and have added the geolocator package. It also assumes that Android and iOS permissions are declared as described earlier. A declaration alone does not grant access. Your code must still check the service and permission before reading a position.
What `getCurrentPosition` returns
A position is a snapshot of the device's location at one moment. The geolocator package returns it as a Position object.
| Property | Meaning |
|---|---|
| `latitude` | North-south coordinate in decimal degrees |
| `longitude` | East-west coordinate in decimal degrees |
| `accuracy` | Estimated horizontal error in meters |
| `timestamp` | Time when the location was recorded |
| `altitude` | Height above the reference level, when available |
The accuracy value is an estimate, not a guarantee. A result with an accuracy of 25 means the device estimates that the position is within about 25 meters of the reported point.
A one-time read is useful for showing nearby places, centering a map, or attaching a location to a form submission. It is different from a position stream, which continues producing updates.
Check before reading
There are two independent checks:
- The device's location service must be enabled.
- Your app must have permission to use location.
The service is a device-level switch. Permission belongs to your app. A user can enable the service but deny your app, or grant your app permission while the service is disabled.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
Future<Position> determinePosition() async {
final serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
throw StateError('Turn on location services and try again.');
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied) {
throw StateError('Location permission was denied.');
}
if (permission == LocationPermission.deniedForever) {
throw StateError(
'Location permission is permanently denied. '
'Enable it in the app settings.',
);
}
return Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
),
);
}
Future<void> printPosition() async {
try {
final position = await determinePosition();
print('Latitude: ${position.latitude}');
print('Longitude: ${position.longitude}');
print('Accuracy: ${position.accuracy} meters');
} on TimeoutException {
print('The location request took too long.');
} on LocationServiceDisabledException {
print('Location services are disabled.');
} on PermissionDeniedException {
print('Location permission is unavailable.');
} on StateError catch (error) {
print(error.message);
}
}getCurrentPosition is asynchronous because the operating system may need time to obtain a satellite, Wi-Fi, or cellular reading. Do not block the UI thread while waiting. Call the function from an event handler or another asynchronous operation, then update the widget after the Future completes.
The accuracy setting is a request to the operating system, not a promise. LocationAccuracy.high can use more power and may take longer than LocationAccuracy.low. Choose the lowest accuracy that meets the feature's needs.
The one-time read flow
A successful result does not mean that future requests will succeed. The user can change permission in system settings while the app is paused. When the app resumes, recheck permission before starting another location operation.
Exercise
Why must an app check both location services and app permission before calling getCurrentPosition?
Show answer
They control different things. The service check tells whether the device can provide location data, while the permission check tells whether this app may receive it.