Sub topic 8
Handling permanent denial and sending users to settings
Earlier chapters built the check-then-request flow. This chapter covers what happens when the user says no one time too many. After permanent denial, the system dialog never appears again, and only the user can change the decision in the system settings.
This chapter assumes you can write async Dart, have geolocator (and optionally permission_handler) in pubspec.yaml, and have declared the permissions in AndroidManifest.xml and Info.plist. It also assumes you know the basic permission states.
What permanent denial means
A runtime permission request shows a dialog owned by the operating system. Your app cannot restyle it, and the OS limits how often it appears. Once the OS stops showing it, calling requestPermission() returns immediately with the same result and the user sees nothing.
Permanent denial happens in different ways on each platform.
| Situation | Android | iOS |
|---|---|---|
| First request | Dialog appears | Dialog appears |
| User denies once | Status is "denied". You may ask again. | Status is "denied" at the OS level. You cannot ask again. |
| User denies a second time | From Android 11, the OS treats this as permanent. | Already permanent after the first denial. |
| User picks "Don't allow" or "Don't ask again" | Permanent | Permanent |
| Fix | User enables location in app settings | User enables location in app settings |
The two packages name this state differently:
geolocatorreportsLocationPermission.deniedForever.permission_handlerreportsPermissionStatus.permanentlyDenied.
geolocator also folds the iOS "denied" case into deniedForever. On iOS, a LocationPermission.denied result therefore means "not asked yet", and deniedForever means the user refused.
Decision flow
The flow below shows where permanent denial sits. The service check comes first because turning on the location service does not fix a permission problem, and the reverse is also true.
Modelling the outcome
Returning an exception string, as the short example earlier in the tutorial did, makes the user interface guess what went wrong. A small enum is easier to handle. Each value maps to one thing the interface should do.
import 'package:geolocator/geolocator.dart';
enum LocationAccess { granted, denied, deniedForever, serviceDisabled }
Future<LocationAccess> checkLocationAccess({bool request = false}) async {
if (!await Geolocator.isLocationServiceEnabled()) {
return LocationAccess.serviceDisabled;
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied && request) {
permission = await Geolocator.requestPermission();
}
switch (permission) {
case LocationPermission.always:
case LocationPermission.whileInUse:
return LocationAccess.granted;
case LocationPermission.deniedForever:
return LocationAccess.deniedForever;
case LocationPermission.denied:
case LocationPermission.unableToDetermine:
return LocationAccess.denied;
}
}The request flag keeps the function usable in two ways. Called with request: false, it only reads state, which is what you want when the app resumes. Called with request: true, it may show the dialog, which should happen only after a user action such as tapping a button.
Sending the user to settings
Both packages can open the right screen:
Geolocator.openAppSettings()opens your app's page in the system settings.Geolocator.openLocationSettings()opens the device-wide location switch.openAppSettings()frompermission_handlerdoes the same as the first one.
Each returns a Future<bool> that is true if the settings screen was opened. The future completes when the screen opens, not when the user comes back. You learn about the user's choice by rechecking later.
Opening settings is a significant jump out of your app, so ask first. A dialog that explains the situation and offers a clear choice is the usual pattern.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
enum LocationAccess { granted, denied, deniedForever, serviceDisabled }
Future<LocationAccess> checkLocationAccess({bool request = false}) async {
if (!await Geolocator.isLocationServiceEnabled()) {
return LocationAccess.serviceDisabled;
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied && request) {
permission = await Geolocator.requestPermission();
}
switch (permission) {
case LocationPermission.always:
case LocationPermission.whileInUse:
return LocationAccess.granted;
case LocationPermission.deniedForever:
return LocationAccess.deniedForever;
case LocationPermission.denied:
case LocationPermission.unableToDetermine:
return LocationAccess.denied;
}
}
void main() => runApp(const MaterialApp(home: LocationGate()));
class LocationGate extends StatefulWidget {
const LocationGate({super.key});
@override
State<LocationGate> createState() => _LocationGateState();
}
class _LocationGateState extends State<LocationGate>
with WidgetsBindingObserver {
LocationAccess? _access;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_refresh();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_refresh();
}
}
Future<void> _refresh({bool request = false}) async {
final access = await checkLocationAccess(request: request);
if (mounted) setState(() => _access = access);
}
Future<void> _confirmOpenSettings() async {
final open = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Location is turned off for this app'),
content: const Text(
'To show places near you, allow location in the app settings. '
'You can change this at any time.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Not now'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Open settings'),
),
],
),
);
if (open == true) {
await Geolocator.openAppSettings();
}
}
@override
Widget build(BuildContext context) {
final Widget body;
switch (_access) {
case null:
body = const CircularProgressIndicator();
case LocationAccess.granted:
body = const Text('Location is available.');
case LocationAccess.denied:
body = FilledButton(
onPressed: () => _refresh(request: true),
child: const Text('Allow location'),
);
case LocationAccess.deniedForever:
body = FilledButton(
onPressed: _confirmOpenSettings,
child: const Text('Location is blocked. Fix in settings'),
);
case LocationAccess.serviceDisabled:
body = FilledButton(
onPressed: Geolocator.openLocationSettings,
child: const Text('Turn on device location'),
);
}
return Scaffold(body: Center(child: body));
}
}Four details in this widget matter:
- The permission request runs only from a button press, never from
initState. didChangeAppLifecycleStaterechecks without requesting. When the user returns from settings with the permission enabled, the screen updates by itself.if (mounted)guardssetStatebecause the check is asynchronous and the widget may be gone by the time it finishes.- The "Not now" button leaves the user in a usable state. The app must still work in some form without location.
The same flow with permission_handler
If you already use permission_handler, the equivalent check looks like this:
import 'package:permission_handler/permission_handler.dart';
Future<bool> requestLocationOrExplain(
Future<bool> Function() askToOpenSettings,
) async {
var status = await Permission.locationWhenInUse.status;
if (status.isDenied) {
status = await Permission.locationWhenInUse.request();
}
if (status.isGranted) {
return true;
}
if (status.isPermanentlyDenied && await askToOpenSettings()) {
await openAppSettings();
}
return false;
}permission_handler has one more state that geolocator does not expose directly: isRestricted. It appears on iOS when something like parental controls prevents the user from granting permission. Opening settings does not help in that case, so do not show a settings button for it. Show a message that location is restricted on the device.
Common errors
- Requesting repeatedly. A permanently denied request returns at once. If your button calls
requestPermission()and nothing happens, check fordeniedForeverfirst. - Opening settings without explanation. Users who land on the settings screen with no context often leave without changing anything. Say what to tap, for example "Permissions, then Location, then Allow while using the app".
- Not rechecking on resume. If you read the state once, the screen stays on "blocked" even after the user fixes it.
- Treating service-off as a denial.
openAppSettings()does not help when the device location switch is off. UseopenLocationSettings()for that case. - Blocking the app. If location is optional, offer a fallback such as manual city entry. Only gate the whole app on location when the app cannot work without it.
- Testing only the first run. The state after a reinstall differs from the state after an upgrade. To reproduce permanent denial on Android, deny twice. To reset on iOS, delete the app or use the Simulator's reset option (Device, Erase All Content and Settings, or Reset Location & Privacy in Settings, General, Transfer or Reset).
Design guidance
- Show your own explanation before the system dialog, and a second one before sending the user to settings. The first appeals to the user's goal. The second describes the exact steps.
- Offer an easy way to dismiss, and remember the dismissal for the session so you do not nag.
- Keep the "blocked" state visible in the interface, for example a banner with a settings button, so the user can fix it later without hunting for the setting.
- Do not use dark patterns such as a fake permission dialog. They damage trust, and store reviewers reject them.
Exercise
A user taps "Allow location" in your app on an iOS device and chooses "Don't Allow". They tap your button again. What should your code do, what does Geolocator.checkPermission() return, and which call should the second tap lead to?
Show answer
On iOS the system dialog is shown only once, so checkPermission() returns LocationPermission.deniedForever (geolocator maps the iOS denial to this value). Calling requestPermission() again would show nothing. The second tap should show your own explanation dialog and, if the user agrees, call Geolocator.openAppSettings(). When the app resumes, it should recheck the permission without requesting it.
Exercise
Why does await Geolocator.openAppSettings() not tell you whether the user enabled location, and where should you detect the change instead?
Show answer
The future completes when the settings screen opens, not when the user returns or changes anything. Detect the change by observing the app lifecycle (WidgetsBindingObserver) and calling checkPermission() (without requesting) when the state becomes AppLifecycleState.resumed.