Sub topic 14
Error handling and testing the permission flow
This chapter assumes you have read the earlier chapters of this tutorial. You should know the check-then-request flow, the LocationPermission values from geolocator, and the difference between a disabled location service and a denied permission. You should also be comfortable with async/await, Stream subscriptions, and writing a basic flutter_test test. The examples assume geolocator 10 or later.
Why the happy path is not enough
The flow from earlier chapters returns a Position or throws a string through Future.error. That works in a demo. In a real app the caller has to decide what to show, and a string is a poor thing to branch on. Location code can fail for these reasons:
- The location service is off.
- The user denied the permission once.
- The user denied it permanently.
- The platform declaration is missing, which is a developer error.
- No fix arrives before a time limit.
- A second permission request starts while the first dialog is still open.
Each case needs a different reaction. Some call for a message, some for a button that opens settings, and some for a log entry and a bug fix.
Return typed results instead of strings
Model the outcomes as a sealed class and an enum. The compiler then forces every caller to handle every case.
import 'package:geolocator/geolocator.dart';
enum LocationFailureReason {
serviceDisabled,
denied,
permanentlyDenied,
timeout,
unknown,
}
sealed class LocationResult {
const LocationResult();
}
class LocationSuccess extends LocationResult {
const LocationSuccess(this.position);
final Position position;
}
class LocationFailure extends LocationResult {
const LocationFailure(this.reason);
final LocationFailureReason reason;
}A caller can now use an exhaustive switch. If you add a new result type later, every switch that misses it fails to compile.
Put the plugin behind a small interface
Static calls such as Geolocator.checkPermission() talk to platform channels. Platform channels are not available in a plain unit test. Wrap the calls in an interface that you own. In production you use the real implementation, and in tests you use a fake.
import 'package:geolocator/geolocator.dart';
abstract class LocationGateway {
Future<bool> isServiceEnabled();
Future<LocationPermission> checkPermission();
Future<LocationPermission> requestPermission();
Future<Position> getPosition();
}
class GeolocatorGateway implements LocationGateway {
const GeolocatorGateway();
@override
Future<bool> isServiceEnabled() => Geolocator.isLocationServiceEnabled();
@override
Future<LocationPermission> checkPermission() => Geolocator.checkPermission();
@override
Future<LocationPermission> requestPermission() =>
Geolocator.requestPermission();
@override
Future<Position> getPosition() => Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
timeLimit: Duration(seconds: 15),
),
);
}The timeLimit makes getCurrentPosition throw a TimeoutException when no fix arrives in time. Without it, a call indoors or in airplane mode can wait for a long time.
The service that maps everything to a result
Save this as lib/location_service.dart next to the gateway and result types.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
class LocationService {
LocationService(this._gateway);
final LocationGateway _gateway;
Future<LocationResult> locate() async {
try {
if (!await _gateway.isServiceEnabled()) {
return const LocationFailure(LocationFailureReason.serviceDisabled);
}
var permission = await _gateway.checkPermission();
if (permission == LocationPermission.denied) {
permission = await _gateway.requestPermission();
}
switch (permission) {
case LocationPermission.denied:
return const LocationFailure(LocationFailureReason.denied);
case LocationPermission.deniedForever:
return const LocationFailure(LocationFailureReason.permanentlyDenied);
case LocationPermission.unableToDetermine:
return const LocationFailure(LocationFailureReason.unknown);
case LocationPermission.whileInUse:
case LocationPermission.always:
return LocationSuccess(await _gateway.getPosition());
}
} on TimeoutException {
return const LocationFailure(LocationFailureReason.timeout);
} on LocationServiceDisabledException {
return const LocationFailure(LocationFailureReason.serviceDisabled);
} on PermissionDeniedException {
return const LocationFailure(LocationFailureReason.denied);
} catch (_) {
return const LocationFailure(LocationFailureReason.unknown);
}
}
}The try block also catches exceptions the earlier checks cannot predict. The user can switch the service off between your check and the read. The permission can be revoked in settings while the dialog is open. Both cases are real, because the state you checked is only a snapshot.
Exceptions you will meet
| Exception | Typical cause | Right reaction |
|---|---|---|
| `LocationServiceDisabledException` | Service turned off | Offer to open location settings |
| `PermissionDeniedException` | Permission missing or revoked | Run the request flow again |
| `PermissionDefinitionsNotFoundException` | Manifest or `Info.plist` entry missing | Fix the app, log it |
| `PermissionRequestInProgressException` | A second request started while a dialog was open | Ignore the second call or reuse the first future |
| `ActivityMissingException` | Android could not find an activity to show a dialog | Retry when the app is in the foreground |
| `TimeoutException` (from `dart:async`) | No fix before `timeLimit` | Offer a retry or use the last known position |
The missing-declaration error is a bug, not a user state. Do not show it to the user as "permission denied". Log it loudly in debug builds.
Mapping results to the screen
In the widget, an exhaustive switch expression keeps this mapping honest:
String messageFor(LocationResult result) {
return switch (result) {
LocationSuccess(:final position) =>
'You are at ${position.latitude}, ${position.longitude}',
LocationFailure(:final reason) => switch (reason) {
LocationFailureReason.serviceDisabled =>
'Turn on location services to continue.',
LocationFailureReason.denied =>
'Location is needed to show nearby places.',
LocationFailureReason.permanentlyDenied =>
'Location is blocked. Enable it in app settings.',
LocationFailureReason.timeout =>
'No location fix yet. Try again.',
LocationFailureReason.unknown =>
'Something went wrong. Try again later.',
},
};
}Errors on a stream
A stream reports errors through its onError callback. If you omit it, an uncaught error reaches the zone's error handler and can crash a release build.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
StreamSubscription<Position>? _subscription;
void startTracking(void Function(Position) onPosition) {
const settings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 50,
);
_subscription = Geolocator.getPositionStream(locationSettings: settings)
.listen(
onPosition,
onError: (Object error) {
if (error is LocationServiceDisabledException ||
error is PermissionDeniedException) {
_subscription?.cancel();
_subscription = null;
}
},
);
}The user can turn location off while a stream is active, and the stream may then report an error. Cancel the subscription in that case, then wait for the app to resume or for the user to act before you restart it.
Testing the permission flow without a device
Write the logic tests against a fake gateway. They run in milliseconds and cover states that are tedious to reach on a phone, such as permanent denial.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:geolocator/geolocator.dart';
import 'package:my_app/location_service.dart';
class FakeGateway implements LocationGateway {
FakeGateway({
this.serviceEnabled = true,
this.initial = LocationPermission.denied,
this.afterRequest = LocationPermission.denied,
this.positionError,
});
final bool serviceEnabled;
final LocationPermission initial;
final LocationPermission afterRequest;
final Object? positionError;
int requestCalls = 0;
@override
Future<bool> isServiceEnabled() async => serviceEnabled;
@override
Future<LocationPermission> checkPermission() async => initial;
@override
Future<LocationPermission> requestPermission() async {
requestCalls++;
return afterRequest;
}
@override
Future<Position> getPosition() async {
if (positionError != null) throw positionError!;
return Position(
latitude: 52.52,
longitude: 13.405,
timestamp: DateTime.utc(2026, 1, 1),
accuracy: 5,
altitude: 0,
altitudeAccuracy: 0,
heading: 0,
headingAccuracy: 0,
speed: 0,
speedAccuracy: 0,
);
}
}
void main() {
test('service off skips the permission request', () async {
final gateway = FakeGateway(serviceEnabled: false);
final result = await LocationService(gateway).locate();
expect(result, isA<LocationFailure>());
expect((result as LocationFailure).reason,
LocationFailureReason.serviceDisabled);
expect(gateway.requestCalls, 0);
});
test('denied, then granted, returns a position', () async {
final gateway =
FakeGateway(afterRequest: LocationPermission.whileInUse);
final result = await LocationService(gateway).locate();
expect(result, isA<LocationSuccess>());
expect(gateway.requestCalls, 1);
});
test('permanent denial never asks again', () async {
final gateway = FakeGateway(initial: LocationPermission.deniedForever);
final result = await LocationService(gateway).locate();
expect((result as LocationFailure).reason,
LocationFailureReason.permanentlyDenied);
expect(gateway.requestCalls, 0);
});
test('a slow fix becomes a timeout failure', () async {
final gateway = FakeGateway(
initial: LocationPermission.whileInUse,
positionError: TimeoutException('no fix'),
);
final result = await LocationService(gateway).locate();
expect((result as LocationFailure).reason, LocationFailureReason.timeout);
});
}For widget tests, pass the LocationService or the gateway into your widget through its constructor or your dependency injection setup. Then pump the widget with a fake that returns each failure and assert that the right text and buttons appear.
If you use permission_handler directly, wrap Permission.locationWhenInUse.request() in the same kind of interface. Do not rely on mocking the plugin's internals.
What the fake cannot tell you
A fake proves your branching logic. It cannot prove that your platform declarations are correct or that the real dialogs behave as expected. Check those on an emulator or simulator.
| Scenario | Android emulator | iOS simulator |
|---|---|---|
| Set a fake position | Extended controls, Location | Features, Location |
| Reset the permission | `adb shell pm revoke <package> android.permission.ACCESS_FINE_LOCATION` | `xcrun simctl privacy booted reset location <bundle-id>` |
| Force permanent denial | Deny twice in the dialog | Choose "Don't Allow", then check the state |
| Service off | Turn off Location in quick settings | Settings, Privacy, Location Services |
| Missing declaration | Remove the manifest entry and run | Remove the `Info.plist` key and run |
A short checklist
- Every outcome of
locate()has a distinct, user-facing reaction. getCurrentPositionhas atimeLimit.- Every
listencall has anonErrorhandler, and the subscription is cancelled on dispose. - Logic tests cover service off, denied then granted, permanent denial, and timeout.
- A manual pass on both platforms covers the real dialogs and settings redirects.
Exercise
Your test for permanent denial passes with the fake gateway, but on a real Android device the app shows "denied" and asks again instead of offering settings. Name two likely causes outside the LocationService branching logic.
Show answer
First, the fake returns deniedForever directly, while a real device may report denied after a single refusal, because the platform only reports permanent denial after a later check or a second refusal. Make sure your manual test denies the dialog twice. Second, the app may have called requestPermission() before checkPermission() on a state the platform already treats as blocked, so the dialog never appears and the result stays denied. Always read the state again after the request and map deniedForever to the settings action.
Exercise
Add a test to the suite above that checks that locate() returns LocationFailureReason.denied when the user refuses the dialog. What must the FakeGateway be configured with, and what should the test assert about requestCalls?
Show answer
Use FakeGateway() with its defaults: initial is LocationPermission.denied and afterRequest is also LocationPermission.denied. Call LocationService(gateway).locate(), expect a LocationFailure with reason LocationFailureReason.denied, and expect gateway.requestCalls to equal 1, because the service asked once and did not loop.