Sub topic 1
How Runtime Permissions Work on Android and iOS
Prerequisites
You should know basic Dart and Flutter widgets, use async/await with Futures, and add packages through pubspec.yaml. You should also be able to open the android and ios folders of a Flutter project.
Location is sensitive data. Before an app can read it, two things must happen. The app declares the permission in its platform files, and the user grants it at runtime through a system dialog. The user can change the answer later in system settings.
Runtime Grants on Each Platform
Android 6.0 (API 23) and later ask for dangerous permissions, including location, while the app runs. iOS asks the first time the app uses location. Both platforms remember the answer.
Choosing Packages
geolocatorreads the device position and reports whether location services are on.permission_handlerrequests and checks the permission status of the app.
Use both when you need to tell "location services are off" apart from "permission is denied."
Declaring Permissions
On Android, add these lines to android/app/src/main/AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application android:label="my_app">
...
</application>
</manifest>On iOS, add this key to ios/Runner/Info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>We use your location to show nearby places while the app is open.</string>> Without the iOS usage string, the app crashes when it requests location.
Reading Permission States
| State | Package | Meaning | Next step |
|---|---|---|---|
| granted | permission_handler | The user allowed access | Read the position |
| denied | permission_handler | The user refused, and the app can ask again | Request again with a reason |
| permanentlyDenied | permission_handler | The user chose not to be asked again | Open app settings |
| deniedForever | geolocator | Same as permanentlyDenied | Open app settings |
caption: Decision flow for a location request, checking the service first and then the permission. alt: A flowchart that checks whether location services are on, then branches on the permission state into requesting, opening settings, or reading the position.
:::callout note Android 12 and later let users grant approximate location only. Your app must handle a coarse fix even when it requests fine location. :::
Exercise
A user denies location twice on Android and selects "Don't ask again." What should the app do next?
Show answer
Stop requesting. Explain why location is needed, then send the user to app settings with openAppSettings(), and check the status again when the app resumes.