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)),
],
);
}
}
|