Sub topic 5
Location services off versus permission denied
This chapter assumes you can write async Dart, have geolocator in your pubspec.yaml, and know the permission states from the previous chapter (denied, deniedForever, whileInUse, always). Here you separate two failures that look identical to a user ("my location doesn't work") but have different causes and different fixes.
Two independent switches
Location access depends on two separate conditions:
- The location service is a device-wide switch. On Android it is the Location toggle in quick settings. On iOS it is Settings > Privacy & Security > Location Services. When it is off, no app on the device can read a position.
- The app permission is a per-app grant that the user gives or refuses. It is the dialog your app triggers, and it is also shown in the app's own settings page.
Both must be true before a position can be read. Neither implies the other. A user can grant your app permission and later turn the service off. A user can also leave the service on and deny your app.
| Service | Permission | Result | Who can fix it |
|---|---|---|---|
| On | Granted | Positions are delivered | Nothing to fix |
| On | Denied | Your app gets no position | The user, after you ask again |
| On | Permanently denied | Your app gets no position, and the dialog will not appear | The user, in app settings |
| Off | Granted | Your app gets no position | The user, in device location settings |
| Off | Denied | Your app gets no position | The user, in two places |
The "Who can fix it" column drives your interface. Asking for permission cannot help when the service is off, and sending someone to the device location settings cannot help when the app is denied.
Checking the service
Geolocator.isLocationServiceEnabled() returns a Future<bool>. It reports the device switch and says nothing about your app's permission.
import 'package:geolocator/geolocator.dart';
Future<void> printServiceState() async {
final enabled = await Geolocator.isLocationServiceEnabled();
print(enabled ? 'Service is on' : 'Service is off');
}If you use permission_handler instead, the equivalent is Permission.location.serviceStatus, which returns a ServiceStatus. Its values are enabled, disabled, and notApplicable. The last one appears for permissions that have no service behind them, so a location check should compare against ServiceStatus.enabled rather than assume a two-value result.
import 'package:permission_handler/permission_handler.dart';
Future<bool> isServiceOn() async {
final status = await Permission.location.serviceStatus;
return status == ServiceStatus.enabled;
}Check the service first
The order in your flow matters. Check the service before you ask for permission, for these reasons:
- A permission prompt is a wasted prompt when the service is off. The user may answer it, then find that nothing works. A user who feels tricked is more likely to deny.
- Platform behavior differs. On Android you can query and request permission while the service is off. On iOS, a request made while Location Services is off may not show the usual dialog. Checking the service first avoids depending on this difference.
- The two failures need different messages. If you check permission first and then fail on the service, you may show an "allow location" message to someone who already allowed it.
Wrap the check and the permission logic in one function that returns a typed result instead of throwing strings. A caller can then choose the right interface for each case.
import 'package:geolocator/geolocator.dart';
enum LocationGate { ready, serviceOff, denied, deniedForever }
Future<LocationGate> checkLocationGate({bool request = true}) async {
if (!await Geolocator.isLocationServiceEnabled()) {
return LocationGate.serviceOff;
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied && request) {
permission = await Geolocator.requestPermission();
}
switch (permission) {
case LocationPermission.whileInUse:
case LocationPermission.always:
return LocationGate.ready;
case LocationPermission.deniedForever:
return LocationGate.deniedForever;
case LocationPermission.denied:
case LocationPermission.unableToDetermine:
return LocationGate.denied;
}
}The request parameter lets you check silently, for example when the app resumes, without raising a dialog the user did not expect. The switch has no default on purpose. Dart then reports an error if a future version of the package adds a new enum value, and you can decide how to treat it.
Sending the user to the right settings screen
Each failure has its own settings destination in geolocator:
Geolocator.openLocationSettings()opens the device location settings. Use it forserviceOff.Geolocator.openAppSettings()opens your app's page in system settings. Use it fordeniedForever.
Both return a Future<bool> that tells you whether the settings screen could be opened. They do not tell you what the user did there.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LocationProblemBanner extends StatelessWidget {
const LocationProblemBanner({super.key, required this.problem});
final LocationGate problem;
@override
Widget build(BuildContext context) {
switch (problem) {
case LocationGate.serviceOff:
return _Banner(
message: 'Location is turned off on this device.',
action: 'Turn on location',
onPressed: Geolocator.openLocationSettings,
);
case LocationGate.deniedForever:
return _Banner(
message: 'Location access is blocked for this app.',
action: 'Open app settings',
onPressed: Geolocator.openAppSettings,
);
case LocationGate.denied:
return const Text('Allow location to see nearby places.');
case LocationGate.ready:
return const SizedBox.shrink();
}
}
}
class _Banner extends StatelessWidget {
const _Banner({
required this.message,
required this.action,
required this.onPressed,
});
final String message;
final String action;
final Future<bool> Function() onPressed;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(child: Text(message)),
TextButton(onPressed: onPressed, child: Text(action)),
],
);
}
}This widget uses LocationGate from the previous listing. The two settings buttons never appear together, because each failure has one fix.
Reacting when the service changes
The user changes the service switch outside your app, often from the notification shade while your app is still running. Geolocator.getServiceStatusStream() emits a ServiceStatus (enabled or disabled) whenever the switch changes, so your interface can update without a manual refresh.
import 'dart:async';
import 'package:geolocator/geolocator.dart';
StreamSubscription<ServiceStatus>? _serviceSub;
void watchService(void Function(bool enabled) onChanged) {
_serviceSub = Geolocator.getServiceStatusStream().listen((status) {
onChanged(status == ServiceStatus.enabled);
});
}
void stopWatchingService() {
_serviceSub?.cancel();
_serviceSub = null;
}Cancel this subscription when the screen is disposed, as you will for position streams in a later chapter. A forgotten listener keeps running and can call into a widget that no longer exists.
Catching the failure at the point of use
Even with a good pre-check, the state can change between your check and your read. The user may toggle the service in the instant after your check passes. Treat the check as a way to guide the user, and treat exceptions as the final authority. getCurrentPosition throws a different exception for each cause:
import 'package:geolocator/geolocator.dart';
Future<Position?> tryGetPosition() async {
try {
return await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(accuracy: LocationAccuracy.high),
);
} on LocationServiceDisabledException {
print('The location service was turned off.');
} on PermissionDeniedException {
print('The app does not have location permission.');
}
return null;
}LocationServiceDisabledException and PermissionDeniedException correspond directly to the two switches in this chapter. Catching them separately lets you route to the same banner as the pre-check does.
Common mistakes
- Treating
isLocationServiceEnabled()as a permission check. It returnstruefor an app that has been denied. - Requesting permission while the service is off. It wastes a prompt and may behave differently on each platform.
- Showing one generic error. "Location unavailable" gives the user no next step. Name the cause and offer the matching settings button.
- Assuming the state persists. Both switches can change while the app is in the background. Recheck on resume.
- Opening app settings for a service problem. The user finds nothing to change there.
Exercise
A user taps "Find nearby places". Geolocator.isLocationServiceEnabled() returns true, and Geolocator.checkPermission() returns LocationPermission.deniedForever. Which settings call should your app offer, and why would Geolocator.openLocationSettings() not help?
Show answer
Offer Geolocator.openAppSettings(). The device location service is already on, so the device-wide switch is not the problem. The app is permanently denied, so the system will not show the permission dialog again, and the user can only change this on the app's page in system settings. openLocationSettings() opens the device-wide switch, which is already on.
Exercise
Your app passes the service and permission checks, then calls getCurrentPosition a moment later and receives a LocationServiceDisabledException. How can that happen, and how should the code respond?
Show answer
The user can turn the location service off between your check and your read, for example from the notification shade. The check only reflects one instant. Catch LocationServiceDisabledException around the read and show the same "location is turned off" message with a button that calls Geolocator.openLocationSettings().