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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
| import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(const MaterialApp(home: PermissionsDemo()));
// ── Definición de permisos con metadatos ───────────────────────────────────────
class PermissionItem {
final Permission permission;
final String name;
final IconData icon;
final String rationale; // Explicación contextual al usuario
const PermissionItem({
required this.permission,
required this.name,
required this.icon,
required this.rationale,
});
}
const _permissions = [
PermissionItem(
permission: Permission.camera,
name: 'Cámara',
icon: Icons.camera_alt,
rationale: 'Necesitamos acceso a la cámara para escanear documentos y QR.',
),
PermissionItem(
permission: Permission.microphone,
name: 'Micrófono',
icon: Icons.mic,
rationale: 'Usamos el micrófono para grabar notas de voz.',
),
PermissionItem(
permission: Permission.locationWhenInUse,
name: 'Localización',
icon: Icons.location_on,
rationale: 'Tu localización nos permite mostrarte tiendas cercanas.',
),
];
// ── Pantalla principal ─────────────────────────────────────────────────────────
class PermissionsDemo extends StatefulWidget {
const PermissionsDemo({super.key});
@override
State<PermissionsDemo> createState() => _PermissionsDemoState();
}
class _PermissionsDemoState extends State<PermissionsDemo>
with WidgetsBindingObserver {
// Estado actual de cada permiso
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();
}
// Actualizar estados al volver desde Ajustes del sistema
@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;
});
}
// Solicitar un permiso individual con rationale previo
Future<void> _requestPermission(PermissionItem item) async {
final current = _statuses[item.permission];
// Si está denegado permanentemente → abrir ajustes
if (current == PermissionStatus.permanentlyDenied) {
_showPermanentlyDeniedDialog(item);
return;
}
// Mostrar rationale si aún no se ha concedido
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) {
if (mounted) _showPermanentlyDeniedDialog(item);
}
}
// Solicitar todos los permisos a la vez
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('Todos los permisos ya están concedidos ✅')),
);
return;
}
// Solicitar en bloque
final results = await [
for (final p in notGranted) p.permission
].request();
setState(() {
for (final entry in results.entries) {
_statuses[entry.key] = entry.value;
}
});
// Si alguno quedó permanentemente denegado, informar
final denied = results.entries
.where((e) => e.value == PermissionStatus.permanentlyDenied)
.toList();
if (denied.isNotEmpty && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'${denied.length} permiso(s) denegados permanentemente. '
'Ve a Ajustes para habilitarlos.'),
action: SnackBarAction(
label: 'Ajustes',
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('Permiso: ${item.name}'),
],
),
content: Text(item.rationale),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('No ahora'),
),
FilledButton(
onPressed: () => Navigator.pop(ctx, true),
child: const Text('Continuar'),
),
],
),
) ??
false;
}
void _showPermanentlyDeniedDialog(PermissionItem item) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Permiso denegado permanentemente'),
content: Text(
'El permiso "${item.name}" fue denegado permanentemente. '
'Para habilitarlo, ve a Ajustes > Aplicaciones > ${item.name}.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Cancelar'),
),
FilledButton(
onPressed: () {
Navigator.pop(ctx);
openAppSettings(); // Abre los ajustes del sistema
},
child: const Text('Abrir Ajustes'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Permisos con permission_handler'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Verificar estados',
onPressed: _checkAll,
),
],
),
body: _loading
? const Center(child: CircularProgressIndicator())
: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ── Lista de permisos ─────────────────────────────────
...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('Solicitar todos los permisos'),
),
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: openAppSettings,
icon: const Icon(Icons.settings),
label: const Text('Abrir Ajustes del sistema'),
),
const Spacer(),
// ── Leyenda ────────────────────────────────────────────
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;
case PermissionStatus.restricted: return Colors.grey;
default: return Colors.grey;
}
}
String _statusLabel(PermissionStatus? s) {
switch (s) {
case PermissionStatus.granted: return 'Concedido — toca para revocar en Ajustes';
case PermissionStatus.denied: return 'Denegado — toca para solicitar';
case PermissionStatus.permanentlyDenied: return 'Denegado permanentemente — toca para ir a Ajustes';
case PermissionStatus.restricted: return 'Restringido por política del dispositivo';
case PermissionStatus.limited: return 'Acceso limitado (iOS)';
default: return 'Estado desconocido';
}
}
}
// ── Chip de estado ─────────────────────────────────────────────────────────────
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 => ('⚠️ Deneg.', 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,
);
}
}
// ── Leyenda ────────────────────────────────────────────────────────────────────
class _Legend extends StatelessWidget {
const _Legend();
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Estados de permiso:',
style: Theme.of(context).textTheme.labelMedium),
const SizedBox(height: 4),
const Text('✅ granted — acceso concedido', style: TextStyle(fontSize: 12)),
const Text('⚠️ denied — denegado (puede volver a pedir)', style: TextStyle(fontSize: 12)),
const Text('🚫 permanentlyDenied — solo desde Ajustes', style: TextStyle(fontSize: 12)),
const Text('🔒 restricted — bloqueado por MDM/parental controls', style: TextStyle(fontSize: 12)),
],
);
}
}
|