Sub topic 12
Cancelling subscriptions and rechecking on resume
This chapter assumes basic Dart and Flutter widget knowledge, async/await, Futures, Streams, and the geolocator package. You should also know how to edit a StatefulWidget.
A position stream can continue producing location updates while your screen no longer needs them. Each update may use GPS, battery, and network resources. A stream subscription is the object that controls this listener. Cancel it when tracking should stop, and always cancel it when the widget is disposed.
The app should also recheck location state when it returns to the foreground. A user may have changed the permission or enabled location services in the system settings while your app was paused.
Connect the stream to the widget lifecycle
Flutter reports app lifecycle changes through WidgetsBindingObserver. The resumed state means that the app is visible and can receive user input again.
A practical policy is:
- Start tracking only when the screen is active and permission is granted.
- Stop tracking when the app is paused or the screen is removed.
- Recheck permission and the location service when the app resumes.
- Avoid creating a second subscription if one is already active.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class TrackingPage extends StatefulWidget {
const TrackingPage({super.key});
@override
State<TrackingPage> createState() => _TrackingPageState();
}
class _TrackingPageState extends State<TrackingPage>
with WidgetsBindingObserver {
StreamSubscription<Position>? _positionSubscription;
Position? _lastPosition;
String _message = 'Tracking is stopped.';
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_checkAndStart();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_checkAndStart();
} else if (state == AppLifecycleState.paused ||
state == AppLifecycleState.inactive) {
_stopTracking();
}
}
Future<void> _checkAndStart() async {
if (_positionSubscription != null) {
return;
}
final serviceEnabled = await Geolocator.isLocationServiceEnabled();
final permission = await Geolocator.checkPermission();
if (!serviceEnabled ||
permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
if (mounted) {
setState(() {
_message = 'Location is unavailable.';
});
}
return;
}
const settings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
);
_positionSubscription =
Geolocator.getPositionStream(locationSettings: settings).listen(
(position) {
if (!mounted) return;
setState(() {
_lastPosition = position;
_message = 'Tracking location.';
});
},
onError: (Object error) {
if (!mounted) return;
setState(() {
_message = 'Location error: $error';
});
},
);
}
Future<void> _stopTracking() async {
await _positionSubscription?.cancel();
_positionSubscription = null;
if (mounted) {
setState(() {
_message = 'Tracking is stopped.';
});
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_positionSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final position = _lastPosition;
return Scaffold(
appBar: AppBar(title: const Text('Location tracking')),
body: Center(
child: Text(
position == null
? _message
: '${position.latitude}, ${position.longitude}',
),
),
);
}
}The _positionSubscription != null check prevents duplicate listeners. cancel() stops future stream events. The dispose method removes the lifecycle observer and releases the subscription even if the app leaves this page.
Understand the lifecycle decisions
| Event | Action | Reason |
|---|---|---|
| `resumed` | Check state and start | Settings may have changed while away |
| `paused` | Cancel the stream | Save resources when the app is hidden |
| `inactive` | Usually stop | The app may temporarily lose focus |
| `dispose` | Remove observer and cancel | Prevent leaks after the widget is destroyed |
Your product may need tracking while the app is hidden. In that case, stopping on paused is not sufficient. Background tracking requires additional platform declarations, user consent, notification behavior, and store-policy review. Do not keep a foreground stream running accidentally when background tracking is not a product requirement.
Exercise
Why should a location permission be checked again when the app resumes?
Show answer
The user may have changed the permission or enabled the location service in system settings while the app was paused, so the earlier state may be outdated.