Sub topic 11
Streaming position updates
This chapter covers how to listen to continuous position updates with the geolocator package. It assumes you can already do the following:
- Declare the location permissions in
AndroidManifest.xmlandInfo.plist. - Run the check-then-request flow.
- Read a single position with
Geolocator.getCurrentPosition. - Work with Dart
StreamandStreamSubscription.
Why stream instead of polling
getCurrentPosition answers one question: where is the device right now? Many features need more than that, such as a delivery tracker, a run recorder, or a map that follows the user. You could call getCurrentPosition in a Timer.periodic loop, but that has real costs:
- Each call may start a fresh location fix, which wastes battery.
- A fixed interval ignores whether the user actually moved.
- Calls can overlap if one fix takes longer than the timer period.
Geolocator.getPositionStream solves this by giving you a Stream<Position>. The platform location system delivers updates when its own criteria are met, and you react to them as events.
Creating a stream
A position stream is a method call plus a LocationSettings object:
import 'dart:async';
import 'package:geolocator/geolocator.dart';
Stream<Position> createPositionStream() {
const settings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
);
return Geolocator.getPositionStream(locationSettings: settings);
}The two settings matter most:
| Setting | Meaning | Effect |
|---|---|---|
| `accuracy` | How precise the fix should be | Higher accuracy uses more power, because it favors GPS over network-based sources |
| `distanceFilter` | Minimum distance in meters the device must move before a new event is emitted | `0` means "report every update the system produces" |
A distanceFilter of 50 means a user standing still produces no events, and a walking user produces one roughly every 50 meters. Choose the largest filter your feature can tolerate. A turn-by-turn navigation screen might use 5 to 10 meters, while a "stores near you" list might use 200 or more.
Listening and cancelling
The stream is a normal Dart stream, so you attach a listener and keep the returned StreamSubscription. The subscription is the only handle you have for stopping updates.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
class LocationTracker {
StreamSubscription<Position>? _subscription;
bool get isTracking => _subscription != null;
void start(void Function(Position) onPosition,
void Function(Object) onError) {
if (_subscription != null) return; // avoid duplicate listeners
const settings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
);
_subscription = Geolocator.getPositionStream(locationSettings: settings)
.listen(onPosition, onError: onError);
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}The guard if (_subscription != null) return; is not decoration. Without it, a second call to start (from a button tapped twice, or a rebuild that re-runs initState logic) creates a second listener, and the platform keeps two location requests alive. Only one of them is reachable for cancellation afterward.
Cancelling the subscription is what tells the plugin to stop requesting location from the operating system. Leaving a subscription running after the screen is gone keeps the location indicator visible, drains the battery, and can call setState on a disposed widget.
Permission comes first
A stream does not run the permission flow for you. If permission is missing or the location service is off, the stream reports an error instead of position events. Run the same checks you used for getCurrentPosition before subscribing:
import 'dart:async';
import 'package:geolocator/geolocator.dart';
Future<StreamSubscription<Position>> startGuardedTracking(
void Function(Position) onPosition,
void Function(Object) onError,
) async {
if (!await Geolocator.isLocationServiceEnabled()) {
throw StateError('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 StateError('Location permission is not granted.');
}
return Geolocator.getPositionStream(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
),
).listen(onPosition, onError: onError);
}Errors inside the stream
Permission can change after the stream starts. The user can pull down the system shade and turn location off, or open Settings and revoke the permission while your app is in the background. The stream then emits an error event, and depending on the platform and plugin version it may also end.
Always pass onError. If you don't, an error event reaches the zone's uncaught-error handler and can crash a debug session or get reported as an unhandled exception in release builds.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
StreamSubscription<Position> listenSafely() {
return Geolocator.getPositionStream(
locationSettings: const LocationSettings(distanceFilter: 25),
).listen(
(position) {
print('Moved to ${position.latitude}, ${position.longitude}');
},
onError: (Object error) {
if (error is LocationServiceDisabledException) {
print('The user turned location services off.');
} else if (error is PermissionDeniedException) {
print('Permission was revoked.');
} else {
print('Location stream error: $error');
}
},
);
}Treat these errors as state changes, not as crashes. Show a banner such as "Location is off. Turn it on to keep tracking", and offer a way to resume. You can also listen to Geolocator.getServiceStatusStream(), which emits ServiceStatus.enabled and ServiceStatus.disabled, to restart the position stream automatically when the user switches location back on.
Using the stream in a widget
In a StatefulWidget, start the subscription in initState (after the permission checks succeed) and cancel it in dispose.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LiveLocationPage extends StatefulWidget {
const LiveLocationPage({super.key});
@override
State<LiveLocationPage> createState() => _LiveLocationPageState();
}
class _LiveLocationPageState extends State<LiveLocationPage> {
StreamSubscription<Position>? _subscription;
Position? _latest;
String? _error;
@override
void initState() {
super.initState();
_begin();
}
Future<void> _begin() async {
final permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
setState(() => _error = 'Location permission is required.');
return;
}
_subscription = Geolocator.getPositionStream(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 20,
),
).listen(
(position) {
if (!mounted) return;
setState(() => _latest = position);
},
onError: (Object e) {
if (!mounted) return;
setState(() => _error = e.toString());
},
);
}
@override
void dispose() {
_subscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final latest = _latest;
return Scaffold(
appBar: AppBar(title: const Text('Live location')),
body: Center(
child: _error != null
? Text(_error!)
: latest == null
? const Text('Waiting for the first fix...')
: Text(
'${latest.latitude.toStringAsFixed(5)}, '
'${latest.longitude.toStringAsFixed(5)}\n'
'Accuracy: ${latest.accuracy.toStringAsFixed(0)} m',
textAlign: TextAlign.center,
),
),
);
}
}Two details deserve attention. The mounted check protects against an event arriving after the widget has left the tree but before cancellation has fully taken effect. The Waiting for the first fix... state matters because a stream with a distance filter may not emit anything until the device moves, and the first event can take several seconds on a cold GPS start.
Getting a first value quickly
Because a filtered stream stays silent until the user moves, a map screen may look empty at first. A common pattern is to seed the UI with a cached or current position, then let the stream take over:
import 'package:geolocator/geolocator.dart';
Future<Position?> seedPosition() async {
final last = await Geolocator.getLastKnownPosition();
if (last != null) return last;
return Geolocator.getCurrentPosition();
}getLastKnownPosition returns immediately with whatever the system cached, or null if nothing is available. It is not supported on web. The cached value may be old, so check position.timestamp before treating it as the user's present location.
Platform-specific settings
The base LocationSettings works on both platforms. For more control, the plugin offers subclasses:
AndroidSettingsaddsintervalDuration(the requested time between updates) andforceLocationManager. Its foreground notification config is covered in the background-location chapter.AppleSettingsaddsactivityType(such asActivityType.fitness) andpauseLocationUpdatesAutomatically, which lets iOS pause updates when it believes the user has stopped moving.
You can pick between them with defaultTargetPlatform:
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
LocationSettings buildSettings() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 25,
intervalDuration: const Duration(seconds: 10),
);
}
if (defaultTargetPlatform == TargetPlatform.iOS) {
return AppleSettings(
accuracy: LocationAccuracy.high,
activityType: ActivityType.fitness,
distanceFilter: 25,
pauseLocationUpdatesAutomatically: true,
);
}
return const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 25,
);
}Common mistakes
- Subscribing without storing the subscription. You then cannot cancel it. Always keep the
StreamSubscription. - Starting a stream on every rebuild. Put the subscription in
initStateor a long-lived object, never inbuild. - Using
distanceFilter: 0by default. This produces the highest event rate and the highest battery use. Pick a filter that matches the feature. - Omitting
onError. Revoked permission then becomes an unhandled exception. - Assuming the first event arrives immediately. Show a loading state and seed with a cached position.
- Trusting every fix equally.
Position.accuracyis the estimated error radius in meters. Consider ignoring fixes where it is much larger than your filter, since the "movement" may be noise.
Exercise
A fitness screen uses getPositionStream with distanceFilter: 0. Testers report fast battery drain, and the debug console shows an unhandled exception after they revoke location permission in system Settings while the app runs. Name two changes that address these two problems.
Show answer
Set distanceFilter to a meaningful value, such as 10 to 25 meters, so the system reports an update only after real movement. Add an onError callback to listen that handles PermissionDeniedException (and LocationServiceDisabledException), updates the UI, and stops or restarts the subscription as appropriate.
Exercise
Your page calls Geolocator.getPositionStream(...).listen(...) inside build. What goes wrong, and where should the call go?
Show answer
Every rebuild creates another listener, so several location requests stay active and setState is called many times for each fix. Only the latest subscription (if any was stored) can be cancelled. Move the call to initState after the permission checks, store the StreamSubscription in a field, and cancel it in dispose.