Sub topic 6
Building the check-then-request flow
This chapter assumes you can read Dart async/await code and have added geolocator to pubspec.yaml. It also assumes the Android and iOS declarations from the previous chapters are in place: the uses-permission entries in AndroidManifest.xml and NSLocationWhenInUseUsageDescription in Info.plist. Here you combine the pieces into one function that answers a single question: can I read the position right now, and if not, why not?
Why a flow and not a single call
Calling Geolocator.getCurrentPosition() directly looks simpler, but it fails in several unrelated ways:
- The device's location switch is off.
- The user has never been asked for permission.
- The user denied permission once.
- The user denied permission permanently.
Each case needs a different response. The first needs the system location settings. The second and third need a permission dialog. The fourth needs the app settings screen, because no dialog can appear any more. A check-then-request flow separates these cases before you ask for a position, so the UI can react to each one.
The flow follows one rule: check first, request only when the check says a request can help. Requesting blindly wastes your one-time chance at a system dialog and, on a permanently denied permission, does nothing visible.
The decision flow
The service check comes first because it does not depend on the user's choice about your app. If the whole feature is switched off at the device level, showing a permission dialog would not help.
Reading the states
Geolocator.checkPermission() returns a LocationPermission value. Only some of the values appear at each point in the flow:
| Value | Meaning | What your code does |
|---|---|---|
| `denied` | Not granted yet. The user has not been asked, or declined a dialog that can be shown again. | Call `requestPermission()`. |
| `deniedForever` | The system will not show a dialog for this app any more. | Stop. Offer a route to settings. |
| `whileInUse` | Granted while the app is in the foreground. | Proceed. |
| `always` | Granted including background use. | Proceed. |
| `unableToDetermine` | The platform could not report a state. | Treat as a failure and report it. |
The package makes platform differences smaller but does not remove them. On Android, a second dialog refusal (or choosing "Don't ask again" on older versions) leads to deniedForever. On iOS, the system asks only once, so a refusal is reported as deniedForever straight away. The flow works unchanged on both because it branches on the reported value, not on a guess about the platform.
A flow that returns a result, not an exception
The determinePosition() function from the package documentation uses Future.error with strings. That works for a demo, but the caller must compare message text to tell failures apart. A small enum is safer: the compiler checks that every case is handled.
import 'package:geolocator/geolocator.dart';
enum LocationAccess {
granted,
serviceDisabled,
denied,
deniedForever,
}
Future<LocationAccess> ensureLocationAccess() async {
final serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return LocationAccess.serviceDisabled;
}
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
switch (permission) {
case LocationPermission.whileInUse:
case LocationPermission.always:
return LocationAccess.granted;
case LocationPermission.deniedForever:
return LocationAccess.deniedForever;
case LocationPermission.denied:
case LocationPermission.unableToDetermine:
return LocationAccess.denied;
}
}Four details make this version work.
- One request, then re-evaluate. The function calls
requestPermission()once and then runs itsswitchon whatever the permission became. It does not loop. Re-asking in a loop annoys users and, on Android, can push the state todeniedForeversooner. - The
switchis exhaustive. In Dart 3, aswitchstatement over an enum must cover every value. If a latergeolocatorrelease adds a value, the analyzer flags this code instead of letting the new value fall through. - No position is read here. The function only answers "may I?". Reading the position stays a separate step, so you can reuse the check before streaming as well as before a one-time read.
deniedForeveris checked before requesting. IfcheckPermission()already returnsdeniedForever, theifis skipped and you return immediately without calling the platform.
Using the result in the UI
The calling code decides what each outcome looks like. Here is a minimal handler that reads a position when access is granted and otherwise returns a message for the UI:
import 'package:geolocator/geolocator.dart';
Future<String> describeCurrentLocation() async {
final access = await ensureLocationAccess();
switch (access) {
case LocationAccess.granted:
final position = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
),
);
return '${position.latitude}, ${position.longitude}';
case LocationAccess.serviceDisabled:
return 'Turn on location services to continue.';
case LocationAccess.denied:
return 'Location permission is needed for this feature.';
case LocationAccess.deniedForever:
return 'Enable location for this app in Settings.';
}
}In a real screen, each message would be a button or banner. The two Settings outcomes should link to real settings screens. Geolocator.openLocationSettings() opens the device location switch, and Geolocator.openAppSettings() opens the page for your app. A later chapter covers the wording and the redirect for permanent denial in detail, so here you only need to keep the outcome distinct.
The same flow with permission_handler
You can build the flow with permission_handler instead. It uses a PermissionStatus and exposes request() on a Permission object:
import 'package:permission_handler/permission_handler.dart';
Future<bool> ensureLocationPermission() async {
final status = await Permission.locationWhenInUse.request();
if (status.isGranted) {
return true;
}
if (status.isPermanentlyDenied) {
await openAppSettings();
}
return false;
}Notice what this version leaves out. It never checks whether the location service is on, and it jumps straight to request(). Calling request() on an already granted permission returns granted without a dialog, so the shortcut is safe. It also opens settings immediately, without asking the user first. Use this form when you only need the permission and want to keep the code small. Use the geolocator form when you need to tell "service off" apart from "permission denied", because only that form checks the service.
Common mistakes
- Requesting before checking. The code works but loses information. You cannot tell whether a dialog appeared or the call returned silently.
- Treating
deniedafter a request as final for all time. It means "not granted now". The user can still change their mind later, so show the feature as unavailable but do not store a permanent flag. - Ignoring the service switch. With the permission granted and the switch off,
getCurrentPosition()throws aLocationServiceDisabledException. The flow's first step prevents this. - Running the flow in
initStatewith no context. A permission dialog appearing at launch, before the user knows why, is more likely to be refused. Call the flow when the user taps the feature that needs location. - Caching the result forever. Users can change permissions in system settings at any time. Run the check again each time you need location, and again when the app returns to the foreground.
Exercises
Exercise
Why does ensureLocationAccess() call isLocationServiceEnabled() before checkPermission(), and what would the user see if the order were reversed and the service were off?
Show answer
The service switch is a device-level setting that is independent of the app's permission. If the service is off, no permission dialog can make location work. With the order reversed, the user could be shown a permission dialog and grant it, and then still get an error or no position because the service is off. Checking the service first lets you send the user to the location settings instead.
Exercise
A user taps your "Find nearby places" button. checkPermission() returns LocationPermission.deniedForever. Which functions should you call next, and which should you avoid?
Show answer
Do not call requestPermission(), because the system will not show a dialog and the call cannot change the state. Return the deniedForever outcome and show a message with a button that calls Geolocator.openAppSettings() (or openAppSettings() from permission_handler), so the user can enable location in the system settings.