Sub topic 12
Cancelling subscriptions and rechecking on resume
This chapter covers what happens after a position stream has started. A stream that is never cancelled keeps the GPS hardware busy and drains the battery. The permission you checked at startup can also become invalid while the app is in the background. You will learn to cancel subscriptions at the right moments and to re-validate access when the user returns to the app.
Assumed prerequisites: you can write async/await code and use Dart Stream and StreamSubscription. You know the State lifecycle of a StatefulWidget (initState, dispose). You have already built the check-then-request flow and the getPositionStream example from earlier chapters.
Why a stream needs an owner
Geolocator.getPositionStream returns a stream that does real work only while it has a listener. Each listen call asks the operating system to start location updates. Those updates stop only when the subscription is cancelled. Nothing stops them for you when the widget that started them goes off screen.
Three failure modes show up in practice:
- Leaked subscription. A widget calls
listenininitStateand never cancels. After the user navigates away, the stream keeps firing and the callback keeps callingsetStateon a disposedState. You get the "setState() called after dispose()" error and a battery drain. - Duplicate subscriptions. A "start tracking" button can be tapped twice. Without a guard, you get two listeners, two sets of updates, and only one reference to cancel.
- Stale permission. The user opens system settings, switches location off, and comes back. Your app still believes the earlier check and shows an old state, or the stream fails with an error.
The fix for all three is the same: keep exactly one StreamSubscription? field, treat null as "not tracking", and tie its lifetime to the lifecycle.
Cancelling correctly
StreamSubscription.cancel() returns a Future, but you rarely need to await it. The important habit is to clear your reference as well, so a later "is tracking?" check is accurate.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
StreamSubscription<Position>? _positionSub;
Future<void> stopTracking() async {
final sub = _positionSub;
_positionSub = null; // clear first so a second call is a no-op
await sub?.cancel();
}Clearing the field before awaiting means two quick calls cannot both try to cancel the same subscription.
Prefer cancelling over pause() here. A paused subscription still buffers events and, depending on the platform implementation, may keep the underlying location request alive. Cancelling releases the request. When you need updates again, create a new subscription.
Which lifecycle events matter
Flutter reports app state through AppLifecycleState. For location work you care about three values:
| State | Meaning | What to do |
|---|---|---|
| `resumed` | App is visible and responding to input | Recheck service and permission, restart tracking if wanted |
| `inactive` | Visible but not receiving input (for example a system dialog, or the app switcher on iOS) | Do nothing |
| `paused` | App is in the background | Cancel foreground-only tracking |
Do not react to inactive. On iOS the permission dialog itself makes the app inactive, and on Android it can cause a pause and resume. If you cancel or re-request on inactive, you can end up reacting to your own dialog.
A lifecycle-aware tracker
The widget below remembers whether the user wants tracking, separately from whether a subscription exists. That distinction lets it cancel on pause and restart on resume without asking the user again. It uses WidgetsBindingObserver, which delivers lifecycle changes to a State object.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(const MaterialApp(home: TrackingPage()));
class TrackingPage extends StatefulWidget {
const TrackingPage({super.key});
@override
State<TrackingPage> createState() => _TrackingPageState();
}
class _TrackingPageState extends State<TrackingPage>
with WidgetsBindingObserver {
StreamSubscription<Position>? _positionSub;
bool _wantsTracking = false; // what the user asked for
Position? _last;
String? _problem;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_positionSub?.cancel();
_positionSub = null;
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed && _wantsTracking) {
_startStream();
} else if (state == AppLifecycleState.paused) {
_stopStream();
}
}
Future<void> _onToggle() async {
if (_wantsTracking) {
_wantsTracking = false;
await _stopStream();
if (mounted) setState(() => _problem = null);
} else {
_wantsTracking = true;
await _startStream();
}
}
Future<void> _startStream() async {
if (_positionSub != null) return; // already tracking
// Check only. Never call requestPermission from a lifecycle callback.
final serviceOn = await Geolocator.isLocationServiceEnabled();
final permission = await Geolocator.checkPermission();
if (!mounted || !_wantsTracking || _positionSub != null) return;
if (!serviceOn) {
setState(() => _problem = 'Location services are off.');
return;
}
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
setState(() => _problem = 'Location permission is not granted.');
return;
}
setState(() => _problem = null);
_positionSub = Geolocator.getPositionStream(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
),
).listen(
(position) {
if (mounted) setState(() => _last = position);
},
onError: (Object error) {
_positionSub = null;
if (mounted) setState(() => _problem = 'Stream stopped: $error');
},
cancelOnError: true,
);
}
Future<void> _stopStream() async {
final sub = _positionSub;
_positionSub = null;
await sub?.cancel();
}
@override
Widget build(BuildContext context) {
final last = _last;
return Scaffold(
appBar: AppBar(title: const Text('Tracking')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(last == null
? 'No position yet'
: '${last.latitude}, ${last.longitude}'),
if (_problem != null) Text(_problem!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _onToggle,
child: Text(_wantsTracking ? 'Stop' : 'Start'),
),
],
),
),
);
}
}Points worth studying in this code:
_wantsTrackingversus_positionSub. The first records intent and survives a pause. The second records whether the OS is currently delivering updates.- The guard at the top of
_startStream. Both the button and the resume handler call it, andresumedcan fire more than once. Without the guard you would create duplicates. - The second guard after the
awaits. The user may have tapped Stop, or another call may have finished first, while the checks ran. Re-reading the state after anawaitavoids acting on old information. cancelOnError: truewithonError. If the platform reports a failure, such as revoked permission, the subscription ends and the field is cleared. The UI shows the problem instead of silently showing the last position forever.disposeremoves the observer and cancels. ForgettingremoveObserverleaks theStateobject.
Why resume only checks, never requests
The resume handler calls checkPermission, not requestPermission. A request shows a system dialog. On Android that dialog can cause the app to pause and resume, so a request inside the resume handler can trigger another request, and you get a loop of dialogs. Requests belong in a user-driven action, such as a button tap, as covered in the request-flow chapter.
If the recheck finds deniedForever or a disabled service, show an explanation and a button that calls openAppSettings() or Geolocator.openLocationSettings(). When the user returns, the resumed event runs the same check again and tracking starts without extra work.
Watching the location switch while the app is open
The user can also pull down the quick settings panel and toggle location without leaving your app. That may not trigger a lifecycle change on every platform. The geolocator package offers a stream for this case.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
StreamSubscription<ServiceStatus>? _serviceSub;
void watchServiceSwitch(void Function(bool enabled) onChanged) {
_serviceSub?.cancel();
_serviceSub = Geolocator.getServiceStatusStream().listen((status) {
onChanged(status == ServiceStatus.enabled);
});
}
void stopWatchingServiceSwitch() {
_serviceSub?.cancel();
_serviceSub = null;
}This is another subscription, so it needs the same ownership rules: one field, cancel in dispose, and cancel when the app pauses if you do not need it in the background. When it reports enabled and the user wants tracking, call your guarded _startStream.
Common mistakes
- Starting the stream in
build.buildruns many times, so each run adds a listener. Start streams from events orinitState. - Using
inactiveas the stop signal. This cancels tracking whenever a dialog appears. - Not checking
mountedafterawait. The widget may have been disposed during the check. - Cancelling in
didChangeDependencies. It runs for reasons unrelated to leaving the screen. - Treating a stream error as final. After
cancelOnError, the subscription is gone. Offer a retry that goes through the same guarded start method.
Exercise
In the tracker above, a user taps Start, grants access, then presses the Home button and later switches location off in system settings before returning to the app. Walk through which methods run and what the screen shows when the user returns.
Show answer
On Home, didChangeAppLifecycleState receives paused, so _stopStream cancels the subscription and sets _positionSub to null. _wantsTracking stays true. When the user returns, resumed arrives and _wantsTracking is true, so _startStream runs. isLocationServiceEnabled() returns false, so it sets _problem to "Location services are off." and does not create a subscription. The last known position stays on screen with the problem message under it. Once the user turns location back on and resumes again, the same check passes and tracking restarts.
Exercise
A teammate adds await Geolocator.requestPermission() inside the resumed branch to "make sure" access is granted. Give two reasons this is a bad idea and say where the request should go instead.
Show answer
First, the permission dialog can pause and resume the app (on Android), so the resume handler fires again and can request again, repeating dialogs. Second, requesting without a user action surprises the user and ignores a previous denial. If the state is deniedForever, the request returns immediately without a dialog, so the call achieves nothing. The request should run from a user-driven action such as a button tap, using the check-then-request flow. The resume handler should only check.