Sub topic 3
Getting the Current Position
This chapter assumes you know basic Dart and Flutter widgets, async/await with Futures, adding packages with pub, and Dart Streams. You should also have the Android permissions and iOS usage strings from the earlier chapter in place.
Reading one position
A position is a latitude and longitude pair, with extra fields such as accuracy. The geolocator package reads it with getCurrentPosition. Check the service and permission first, as the earlier chapter explained, and then read the position once:
import 'package:geolocator/geolocator.dart';
Future<Position> determinePosition() async {
if (!await Geolocator.isLocationServiceEnabled()) {
throw Exception('Location services are disabled.');
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
throw Exception('Location permission is not granted.');
}
return Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(accuracy: LocationAccuracy.high),
);
}Streaming position updates
getPositionStream emits a new Position each time the device moves distanceFilter meters. Store the subscription so you can cancel it later.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
StreamSubscription<Position>? _subscription;
void startTracking() {
const settings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
);
_subscription = Geolocator.getPositionStream(locationSettings: settings)
.listen((position) => print('${position.latitude}, ${position.longitude}'));
}
void stopTracking() {
_subscription?.cancel();
_subscription = null;
}Cancelling subscriptions and rechecking on resume
A stream that keeps running drains the battery. Cancel it in dispose. When the user returns from the app settings, recheck the permission. Mix WidgetsBindingObserver into your state class to receive lifecycle events.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
// Recheck permission here, then call startTracking() if it is granted.
}
}Background location
Background access needs more than the foreground permission. Android 10 and later request ACCESS_BACKGROUND_LOCATION separately. iOS needs an "always" usage string and the location background mode. Google Play reviews background location and expects a clear user-facing reason for it.
::: callout warning Request background access only when your feature truly needs it. Most apps should work with foreground access. :::
Error handling and testing
Wrap calls in try/catch. Put the geolocator calls behind a small service class, so tests can substitute a fake that returns fixed positions or throws errors. This lets you test denied and permanently denied paths without a physical device.
Caption: Decision path before reading a position. Alt: A flowchart where a service check and a permission check each lead to an error, and both passing leads to reading the position.
Exercise
Exercise
Why should you call stopTracking() in dispose, and what happens if you skip it?
Show answer
Calling stopTracking() cancels the position subscription when the widget is removed. Without it, the stream keeps listening and using the device's location hardware, which wastes battery and can keep calling setState on a disposed widget.