Sub topic 11
Streaming Position Updates
This chapter assumes you know basic Dart, Flutter widgets, async and await, and Dart streams. It also assumes that your app already declares location access and has a permission request flow.
A single position is useful for a one-time lookup. Navigation, delivery tracking, and fitness apps need repeated updates. The geolocator package provides these updates through a Dart stream. A stream is an asynchronous sequence of values that arrive over time.
How a position stream works
Geolocator.getPositionStream connects your app to location updates from Android or iOS. Each event contains a Position object with values such as latitude, longitude, speed, heading, and timestamp.
You control update behavior with LocationSettings:
accuracyrequests a balance between precision, speed, and battery use.distanceFilterasks for a new update after the device moves at least that many meters.- Platform-specific settings can add options such as Android foreground notification behavior.
A distance filter of 50 does not guarantee an update exactly every 50 meters. The operating system may delay, combine, or adjust updates to save power.
Subscribe and cancel
Keep the StreamSubscription so that you can cancel it later. Starting a new subscription without cancelling the old one can cause duplicate updates, wasted battery, and repeated state changes.
The following tracker assumes permission has already been granted. The start method still checks the location service and permission so that it fails clearly when the environment changes.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
class LocationTracker {
StreamSubscription<Position>? _subscription;
Future<void> start(void Function(Position) onPosition) async {
if (!await Geolocator.isLocationServiceEnabled()) {
throw StateError('Location services are disabled.');
}
final permission = await Geolocator.checkPermission();
if (permission != LocationPermission.whileInUse &&
permission != LocationPermission.always) {
throw StateError('Location permission is not available.');
}
await _subscription?.cancel();
const settings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
);
_subscription = Geolocator.getPositionStream(
locationSettings: settings,
).listen(
onPosition,
onError: (Object error, StackTrace stackTrace) {
// Record the error or show an appropriate UI message.
print('Location stream error: $error');
},
);
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}The listener receives each Position. In a StatefulWidget, the listener can call setState, but only while the widget is mounted. If the widget is disposed while an update arrives, updating its state can cause an error.
Lifecycle and errors
A subscription remains active until it is cancelled or the stream ends. Stop tracking when the feature no longer needs updates. For example, a map screen might start tracking in initState and cancel in dispose. An app that tracks only while visible should also stop when the app goes into the background.
When the app resumes, check the service and permission again. The user may have disabled location or changed the permission in system settings while the app was paused.
Handle stream errors separately from permission errors. A permission error means the app cannot start tracking. A stream error may mean that the provider temporarily failed or the device lost a usable location signal.
Exercise
Why should an app save and cancel its StreamSubscription<Position>?
Show answer
Saving it lets the app stop updates. Cancelling prevents duplicate listeners, unnecessary battery use, and updates after the related screen or feature is gone.