Sub topic 10
Getting the current position
This chapter covers one-shot location reads with the geolocator package. It assumes you have declared the permissions in AndroidManifest.xml and Info.plist and built the check-then-request flow. It also assumes you are comfortable with async/await and setState.
What a one-shot read does
Geolocator.getCurrentPosition asks the platform for a single fix and returns a Future<Position>. Use it when you need the location once, for example to center a map or to load nearby places when a screen opens. If you need continuous updates, use the position stream from the next chapter.
A single read is not instant. The platform may need to start the GPS chip, wait for satellites, or query Wi-Fi and cell data. On a cold start this can take several seconds. Indoors it can take much longer or never finish. Design the call with that delay in mind.
The minimal safe call
The call only works if the service is on and permission is granted. This version repeats the earlier checks and adds accuracy and a time limit as parameters.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
Future<Position> determinePosition({
LocationAccuracy accuracy = LocationAccuracy.high,
Duration timeLimit = const Duration(seconds: 10),
}) async {
if (!await Geolocator.isLocationServiceEnabled()) {
return Future.error('Location services are disabled.');
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied) {
return Future.error('Location permission was denied.');
}
if (permission == LocationPermission.deniedForever) {
return Future.error('Location permission is permanently denied.');
}
return Geolocator.getCurrentPosition(
locationSettings: LocationSettings(
accuracy: accuracy,
timeLimit: timeLimit,
),
);
}The LocationSettings object carries the accuracy and the time limit. Older versions of the package used desiredAccuracy and timeLimit as direct arguments. If your project pins an old version, check its API docs before copying this code.
Choosing accuracy and time limit
Higher accuracy costs more battery and time. Pick the lowest level that serves the feature.
| Accuracy | Typical use | Cost |
|---|---|---|
| `LocationAccuracy.lowest` / `low` | City or region, weather | Low, often fast |
| `LocationAccuracy.medium` | Neighborhood-level suggestions | Moderate |
| `LocationAccuracy.high` | Nearby places, navigation start point | Higher, may need GPS |
| `LocationAccuracy.best` | Fitness or survey apps | Highest battery use |
The exact meters behind each level differ between Android and iOS. Treat the levels as hints and read position.accuracy to learn what you actually got.
The timeLimit matters because without it a read can wait indefinitely. When the limit passes, the Future completes with a TimeoutException from dart:async. Choose a limit that matches the screen: 5 to 10 seconds suits a "find places near me" button, while a background refresh can wait longer.
Reading the result
A Position is an immutable snapshot. These are the fields you will use most.
| Field | Meaning |
|---|---|
| `latitude`, `longitude` | Coordinates in degrees |
| `accuracy` | Estimated horizontal error radius in meters. Smaller is better |
| `altitude` | Height in meters, often less reliable than the horizontal position |
| `speed` | Meters per second, `0` when unknown |
| `heading` | Direction of travel in degrees |
| `timestamp` | When the fix was taken, which can be older than "now" |
| `isMocked` | `true` on Android when a mock location provider produced the fix |
Check accuracy before trusting a fix. A position with accuracy of 1500 meters is technically valid but may be useless for a feature that needs street-level precision.
To measure distance between two points, use Geolocator.distanceBetween(startLat, startLng, endLat, endLng). It returns meters as a double.
final meters = Geolocator.distanceBetween(
position.latitude,
position.longitude,
48.8584, // Eiffel Tower latitude
2.2945, // Eiffel Tower longitude
);Falling back to the last known position
Geolocator.getLastKnownPosition() returns the most recent fix cached by the operating system, or null if none exists. It returns almost immediately and costs no extra battery. The trade-off is that the fix may be minutes or hours old, so always inspect timestamp.
A common pattern is to try for a fresh fix and use the cached one when the fresh read times out.
Future<Position?> positionWithFallback() async {
try {
return await determinePosition(
timeLimit: const Duration(seconds: 8),
);
} on TimeoutException {
return Geolocator.getLastKnownPosition();
}
}The Future.error calls inside determinePosition throw String values here, so this function lets them propagate to the caller. The caller handles them in the widget below.
Using the read in a widget
This complete app shows the position, the accuracy, and any error. It uses a loading flag so a double tap cannot start two reads.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(const MaterialApp(home: PositionPage()));
Future<Position> determinePosition() async {
if (!await Geolocator.isLocationServiceEnabled()) {
return Future.error('Location services are disabled.');
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied) {
return Future.error('Location permission was denied.');
}
if (permission == LocationPermission.deniedForever) {
return Future.error('Location permission is permanently denied.');
}
return Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
timeLimit: Duration(seconds: 10),
),
);
}
class PositionPage extends StatefulWidget {
const PositionPage({super.key});
@override
State<PositionPage> createState() => _PositionPageState();
}
class _PositionPageState extends State<PositionPage> {
Position? _position;
String? _error;
bool _loading = false;
Future<void> _load() async {
if (_loading) return;
setState(() {
_loading = true;
_error = null;
});
Position? result;
String? error;
try {
result = await determinePosition();
} on TimeoutException {
result = await Geolocator.getLastKnownPosition();
if (result == null) error = 'No location fix. Try again outdoors.';
} catch (e) {
error = e.toString();
}
if (!mounted) return;
setState(() {
_position = result ?? _position;
_error = error;
_loading = false;
});
}
@override
Widget build(BuildContext context) {
final p = _position;
return Scaffold(
appBar: AppBar(title: const Text('Current position')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (p != null)
Text('${p.latitude.toStringAsFixed(5)}, '
'${p.longitude.toStringAsFixed(5)}\n'
'accuracy: ${p.accuracy.toStringAsFixed(0)} m\n'
'taken: ${p.timestamp}'),
if (_error != null) Text(_error!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loading ? null : _load,
child: Text(_loading ? 'Locating...' : 'Get my location'),
),
],
),
),
);
}
}The mounted check after the await prevents calling setState on a widget the user has already left. This is the most common crash in location code, because the read can take many seconds.
Common errors and how to read them
LocationServiceDisabledExceptionor your own "services disabled" error. The device switch is off. Offer a button that callsGeolocator.openLocationSettings().PermissionDeniedException. You called the read without a granted permission. Run the check-then-request flow first. The package throws this even if the user revoked access while the app was running.TimeoutException. The fix did not arrive withintimeLimit. Fall back to the cached position or let the user retry.- Works on a phone, hangs on an emulator. Emulators have no real sensors. Set a location in the emulator's extended controls (Android) or through Features, Location in the iOS Simulator. Without one, the read can wait until the timeout.
- A fix far from the real position. Look at
accuracy. A large value means the platform fell back to network-based location. Also checkisMockedif a user could be spoofing.
Edge cases to plan for
- Approximate location. On Android 12 and later, and on iOS 14 and later, the user may grant only approximate location. The read still succeeds, but
accuracywill be a few kilometers. Do not assumehighaccuracy gives you a precise fix. - Permission revoked mid-session. The user can revoke access in system settings while your app is in memory. Always run the checks before a read instead of caching "permission granted" in a variable.
- Repeated reads. If you call
getCurrentPositionevery few seconds, you are building a poor stream. Switch togetPositionStream, which keeps one location session open and uses less power. - Stale cached data. Show the age of a fallback fix, or reject it if
DateTime.now().difference(p.timestamp)exceeds your threshold.
Exercise
A user taps "Find nearby cafes". Your code calls getCurrentPosition with LocationAccuracy.high and no time limit. On some phones the spinner never stops. Name the fix, and say what you should do with the failure.
Show answer
Add a timeLimit in LocationSettings, for example 10 seconds, so the call fails with a TimeoutException instead of waiting forever. Catch the exception and call Geolocator.getLastKnownPosition(). If it returns a position, use it and check its timestamp for age. If it returns null, stop the spinner and show a retry message.
Exercise
Your widget awaits determinePosition() and then calls setState. Users sometimes leave the screen while the read is running, and the app logs an error. What is missing, and where does it go?
Show answer
A mounted check. Add if (!mounted) return; immediately after the await and before setState. The read can finish after the widget has been removed from the tree, and setState on an unmounted State throws an error.