permission_handler in Flutter: solved exercise with full permissions flow

permission_handler in Flutter: solved exercise with full permissions flow

Requesting permissions correctly is one of the leading sources of poor user experience in mobile apps. permission_handler provides a unified API to request and check permissions on Android and iOS, handle the permanentlyDenied state, and open system settings.

Problem statement

Implement a permissions flow that:

  • Checks camera, microphone, and location permission status before requesting.
  • Shows the user context before the system dialog.
  • Handles all four states: granted, denied, permanentlyDenied, restricted.
  • Redirects to system settings when a permission is permanently denied.
  • Requests multiple permissions at once.

Dependencies

1
2
dependencies:
  permission_handler: ^11.3.1

Android setup

In android/app/src/main/AndroidManifest.xml:

1
2
3
4
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

iOS setup

In ios/Runner/Info.plist:

1
2
3
4
5
6
<key>NSCameraUsageDescription</key>
<string>We need camera access to scan documents</string>
<key>NSMicrophoneUsageDescription</key>
<string>We need the microphone to record voice notes</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We use your location to show nearby stores</string>

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(const MaterialApp(home: PermissionsDemo()));

// ── Permission definitions with metadata ───────────────────────────────────────
class PermissionItem {
  final Permission permission;
  final String name;
  final IconData icon;
  final String rationale;

  const PermissionItem({
    required this.permission,
    required this.name,
    required this.icon,
    required this.rationale,
  });
}

const _permissions = [
  PermissionItem(
    permission: Permission.camera,
    name: 'Camera',
    icon: Icons.camera_alt,
    rationale: 'We need camera access to scan documents and QR codes.',
  ),
  PermissionItem(
    permission: Permission.microphone,
    name: 'Microphone',
    icon: Icons.mic,
    rationale: 'We use the microphone to record voice notes.',
  ),
  PermissionItem(
    permission: Permission.locationWhenInUse,
    name: 'Location',
    icon: Icons.location_on,
    rationale: 'Your location lets us show you nearby stores.',
  ),
];

// ── Main screen ────────────────────────────────────────────────────────────────
class PermissionsDemo extends StatefulWidget {
  const PermissionsDemo({super.key});
  @override
  State<PermissionsDemo> createState() => _PermissionsDemoState();
}

class _PermissionsDemoState extends State<PermissionsDemo>
    with WidgetsBindingObserver {
  final _statuses = <Permission, PermissionStatus>{};
  bool _loading = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _checkAll();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // Refresh statuses when returning from system Settings
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) _checkAll();
  }

  Future<void> _checkAll() async {
    setState(() => _loading = true);
    final results = await Future.wait(
      _permissions.map((p) => p.permission.status),
    );
    setState(() {
      for (var i = 0; i < _permissions.length; i++) {
        _statuses[_permissions[i].permission] = results[i];
      }
      _loading = false;
    });
  }

  Future<void> _requestPermission(PermissionItem item) async {
    final current = _statuses[item.permission];

    if (current == PermissionStatus.permanentlyDenied) {
      _showPermanentlyDeniedDialog(item);
      return;
    }

    if (current != PermissionStatus.granted) {
      final proceed = await _showRationaleDialog(item);
      if (!proceed) return;
    }

    final status = await item.permission.request();
    setState(() => _statuses[item.permission] = status);

    if (status == PermissionStatus.permanentlyDenied && mounted) {
      _showPermanentlyDeniedDialog(item);
    }
  }

  Future<void> _requestAll() async {
    final notGranted = _permissions
        .where((p) => _statuses[p.permission] != PermissionStatus.granted)
        .toList();

    if (notGranted.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('All permissions already granted ✅')),
      );
      return;
    }

    final results = await [
      for (final p in notGranted) p.permission
    ].request();

    setState(() {
      for (final entry in results.entries) {
        _statuses[entry.key] = entry.value;
      }
    });

    final denied = results.entries
        .where((e) => e.value == PermissionStatus.permanentlyDenied)
        .toList();
    if (denied.isNotEmpty && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
              '${denied.length} permission(s) permanently denied. '
              'Go to Settings to enable them.'),
          action: SnackBarAction(label: 'Settings', onPressed: openAppSettings),
        ),
      );
    }
  }

  Future<bool> _showRationaleDialog(PermissionItem item) async {
    return await showDialog<bool>(
          context: context,
          builder: (ctx) => AlertDialog(
            title: Row(
              children: [
                Icon(item.icon),
                const SizedBox(width: 8),
                Text('Permission: ${item.name}'),
              ],
            ),
            content: Text(item.rationale),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(ctx, false),
                child: const Text('Not now'),
              ),
              FilledButton(
                onPressed: () => Navigator.pop(ctx, true),
                child: const Text('Continue'),
              ),
            ],
          ),
        ) ??
        false;
  }

  void _showPermanentlyDeniedDialog(PermissionItem item) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Permission permanently denied'),
        content: Text(
          'The "${item.name}" permission was permanently denied. '
          'To enable it, go to Settings > Apps > ${item.name}.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('Cancel'),
          ),
          FilledButton(
            onPressed: () {
              Navigator.pop(ctx);
              openAppSettings();
            },
            child: const Text('Open Settings'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Permissions with permission_handler'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            tooltip: 'Check statuses',
            onPressed: _checkAll,
          ),
        ],
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  ...List.generate(_permissions.length, (i) {
                    final item = _permissions[i];
                    final status = _statuses[item.permission];
                    return Card(
                      margin: const EdgeInsets.only(bottom: 8),
                      child: ListTile(
                        leading: Icon(item.icon, color: _statusColor(status)),
                        title: Text(item.name),
                        subtitle: Text(_statusLabel(status)),
                        trailing: _StatusChip(status: status),
                        onTap: () => _requestPermission(item),
                      ),
                    );
                  }),
                  const SizedBox(height: 8),
                  FilledButton.icon(
                    onPressed: _requestAll,
                    icon: const Icon(Icons.shield),
                    label: const Text('Request all permissions'),
                  ),
                  const SizedBox(height: 8),
                  OutlinedButton.icon(
                    onPressed: openAppSettings,
                    icon: const Icon(Icons.settings),
                    label: const Text('Open system settings'),
                  ),
                  const Spacer(),
                  const _Legend(),
                ],
              ),
            ),
    );
  }

  Color _statusColor(PermissionStatus? s) {
    switch (s) {
      case PermissionStatus.granted: return Colors.green;
      case PermissionStatus.denied: return Colors.orange;
      case PermissionStatus.permanentlyDenied: return Colors.red;
      default: return Colors.grey;
    }
  }

  String _statusLabel(PermissionStatus? s) {
    switch (s) {
      case PermissionStatus.granted: return 'Granted — tap to revoke in Settings';
      case PermissionStatus.denied: return 'Denied — tap to request';
      case PermissionStatus.permanentlyDenied: return 'Permanently denied — tap to open Settings';
      case PermissionStatus.restricted: return 'Restricted by device policy';
      case PermissionStatus.limited: return 'Limited access (iOS)';
      default: return 'Unknown status';
    }
  }
}

class _StatusChip extends StatelessWidget {
  final PermissionStatus? status;
  const _StatusChip({this.status});

  @override
  Widget build(BuildContext context) {
    final (label, color) = switch (status) {
      PermissionStatus.granted => ('✅ OK', Colors.green),
      PermissionStatus.denied => ('⚠️ Denied', Colors.orange),
      PermissionStatus.permanentlyDenied => ('🚫 Perm.', Colors.red),
      PermissionStatus.restricted => ('🔒 Restr.', Colors.grey),
      _ => ('❓', Colors.grey),
    };
    return Chip(
      label: Text(label, style: const TextStyle(fontSize: 11)),
      backgroundColor: color.withOpacity(0.1),
      side: BorderSide(color: color.withOpacity(0.3)),
      padding: EdgeInsets.zero,
      visualDensity: VisualDensity.compact,
    );
  }
}

class _Legend extends StatelessWidget {
  const _Legend();
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Permission statuses:', style: Theme.of(context).textTheme.labelMedium),
        const SizedBox(height: 4),
        const Text('✅ granted — access granted', style: TextStyle(fontSize: 12)),
        const Text('⚠️ denied — denied (can ask again)', style: TextStyle(fontSize: 12)),
        const Text('🚫 permanentlyDenied — only via Settings', style: TextStyle(fontSize: 12)),
        const Text('🔒 restricted — blocked by MDM/parental controls', style: TextStyle(fontSize: 12)),
      ],
    );
  }
}
1
2
3
4
check() → granted? → use feature
        → denied? → show rationale → request() → granted/denied/permanentlyDenied
        → permanentlyDenied? → openAppSettings()
        → restricted? → show explanatory message

Common mistakes

  • Not declaring the permission in AndroidManifest or Info.plist: the plugin returns denied even though the user never saw a dialog. Always check the native config files first.
  • Not refreshing status when returning from Settings: when the user enables a permission in system Settings and returns to the app, the status is not updated automatically. Use WidgetsBindingObserver.didChangeAppLifecycleState to refresh.
  • Showing the system dialog without prior context: Apple and Google may reject your app if you request permissions without first explaining why you need them. Always show a rationale before the native dialog.

Practical use

Any app using camera, location, microphone, notifications, contacts, or Bluetooth needs this flow. It is especially critical in health and fintech apps where permissions are auditable.

Guided practice and next step

FAQ

Can I request permissions before the user reaches the screen that needs them?

Not recommended. Request permissions just before the action that requires them, with a clear rationale. Requesting them at app launch drastically reduces grant rates.

Does permission_handler work on Web and Desktop?

It has limited support. On Web some permissions are managed by the browser. On Desktop (Windows/macOS/Linux) support varies by platform and permission.

What is the difference between denied and permanentlyDenied?

denied means the user rejected the dialog but can be asked again. permanentlyDenied (Android: “Don’t ask again”) means the system will no longer show the dialog — only openAppSettings() can resolve it.