Accesibilidad en Flutter: ejercicio resuelto con Semantics y soporte TalkBack/VoiceOver

Accesibilidad en Flutter: ejercicio resuelto con Semantics y TalkBack/VoiceOver

La accesibilidad es un requisito en apps profesionales y en muchos mercados es exigencia legal (WCAG 2.1, EN 301 549). Flutter ofrece el widget Semantics para describir la UI a los lectores de pantalla (TalkBack en Android, VoiceOver en iOS) sin cambiar la apariencia visual.

Enunciado

Crea una pantalla que:

  • Usa Semantics para etiquetar botones, imágenes e iconos con descripciones útiles.
  • Usa MergeSemantics para agrupar elementos relacionados.
  • Usa ExcludeSemantics para ocultar decoraciones irrelevantes.
  • Implementa focus traversal correcto con FocusTraversalGroup.
  • Respeta el textScaleFactor del sistema (fuentes grandes).
  • Pasa el checklist de accesibilidad de Flutter DevTools.

Dependencias

Ninguna adicional — todo está en el SDK de Flutter.

Solución completa

  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
import 'package:flutter/material.dart';

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

class AccessibilityDemo extends StatefulWidget {
  const AccessibilityDemo({super.key});
  @override
  State<AccessibilityDemo> createState() => _AccessibilityDemoState();
}

class _AccessibilityDemoState extends State<AccessibilityDemo> {
  bool _liked = false;
  bool _subscribed = false;
  int _counter = 0;
  double _volume = 0.5;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Accesibilidad en Flutter')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // ── 1. Imagen con semántica ─────────────────────────────────────
          _SectionTitle('1. Imágenes con descripción semántica'),
          const SizedBox(height: 8),
          Semantics(
            label: 'Ilustración de un teléfono móvil con la aplicación Flutter',
            image: true,
            child: Container(
              height: 120,
              decoration: BoxDecoration(
                color: Colors.blue.shade100,
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Center(
                child: Icon(Icons.phone_android, size: 64, color: Colors.blue),
              ),
            ),
          ),
          const SizedBox(height: 4),
          // Texto decorativo → excluir de la semántica
          ExcludeSemantics(
            child: Text(
              '★★★★★',
              style: TextStyle(color: Colors.amber.shade600, fontSize: 18),
            ),
          ),

          const SizedBox(height: 24),

          // ── 2. Botón con acción semántica personalizada ─────────────────
          _SectionTitle('2. Botón con estado y semántica'),
          const SizedBox(height: 8),
          Semantics(
            label: _liked ? 'Quitar me gusta' : 'Me gusta',
            hint: 'Doble tap para ${_liked ? 'quitar' : 'dar'} me gusta',
            button: true,
            checked: _liked,
            child: GestureDetector(
              onTap: () => setState(() => _liked = !_liked),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                decoration: BoxDecoration(
                  color: _liked ? Colors.red.shade50 : Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(24),
                  border: Border.all(
                    color: _liked ? Colors.red : Colors.grey.shade300,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      _liked ? Icons.favorite : Icons.favorite_border,
                      color: _liked ? Colors.red : Colors.grey,
                    ),
                    const SizedBox(width: 8),
                    Text(_liked ? 'Te gusta' : 'Me gusta'),
                  ],
                ),
              ),
            ),
          ),

          const SizedBox(height: 24),

          // ── 3. MergeSemantics: agrupar texto + imagen ───────────────────
          _SectionTitle('3. MergeSemantics: tarjeta de producto'),
          const SizedBox(height: 8),
          MergeSemantics(
            child: Card(
              child: ListTile(
                // Sin semántica individual → se fusiona en el MergeSemantics
                leading: ExcludeSemantics(
                  child: CircleAvatar(
                    backgroundColor: Colors.green.shade100,
                    child: const Icon(Icons.book, color: Colors.green),
                  ),
                ),
                title: const Text('Flutter en Profundidad'),
                subtitle: const Text('Libro · \$29.99'),
                trailing: Semantics(
                  label: _subscribed ? 'Suscrito' : 'Suscribirse',
                  button: true,
                  child: IconButton(
                    icon: Icon(
                      _subscribed ? Icons.bookmark : Icons.bookmark_border,
                      color: _subscribed ? Colors.green : null,
                    ),
                    onPressed: () => setState(() => _subscribed = !_subscribed),
                  ),
                ),
              ),
            ),
          ),

          const SizedBox(height: 24),

          // ── 4. Contador con semántica de valor ──────────────────────────
          _SectionTitle('4. Contador accesible'),
          const SizedBox(height: 8),
          Semantics(
            label: 'Contador',
            value: '$_counter',
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Semantics(
                  label: 'Decrementar contador',
                  button: true,
                  child: IconButton.filled(
                    onPressed: () => setState(() => _counter--),
                    icon: const Icon(Icons.remove),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 24),
                  child: Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.displaySmall,
                  ),
                ),
                Semantics(
                  label: 'Incrementar contador',
                  button: true,
                  child: IconButton.filled(
                    onPressed: () => setState(() => _counter++),
                    icon: const Icon(Icons.add),
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: 24),

          // ── 5. Slider accesible ─────────────────────────────────────────
          _SectionTitle('5. Slider con semántica de valor'),
          const SizedBox(height: 8),
          Semantics(
            label: 'Control de volumen',
            value: '${(_volume * 100).round()} por ciento',
            increasedValue: '${((_volume + 0.1).clamp(0, 1) * 100).round()} por ciento',
            decreasedValue: '${((_volume - 0.1).clamp(0, 1) * 100).round()} por ciento',
            child: Slider(
              value: _volume,
              onChanged: (v) => setState(() => _volume = v),
              label: '${(_volume * 100).round()}%',
              divisions: 10,
            ),
          ),

          const SizedBox(height: 24),

          // ── 6. Focus traversal ──────────────────────────────────────────
          _SectionTitle('6. Orden de foco correcto'),
          const SizedBox(height: 8),
          FocusTraversalGroup(
            policy: OrderedTraversalPolicy(),
            child: Column(
              children: [
                _FocusableField(order: 1, label: 'Nombre', hint: 'Introduce tu nombre'),
                const SizedBox(height: 8),
                _FocusableField(order: 2, label: 'Email', hint: 'nombre@ejemplo.com'),
                const SizedBox(height: 8),
                _FocusableField(order: 3, label: 'Contraseña', hint: 'Mínimo 8 caracteres', obscure: true),
                const SizedBox(height: 8),
                FocusTraversalOrder(
                  order: const NumericFocusOrder(4),
                  child: FilledButton(
                    onPressed: () {},
                    child: const Text('Crear cuenta'),
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: 24),

          // ── 7. Texto con escala adaptable ───────────────────────────────
          _SectionTitle('7. Texto con escala adaptable'),
          const SizedBox(height: 8),
          // MediaQuery para escala de fuente del sistema
          Builder(builder: (context) {
            final textScale = MediaQuery.textScalerOf(context).scale(1.0);
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Escala actual: ${textScale.toStringAsFixed(2)}x'),
                const SizedBox(height: 4),
                // Respetar siempre el textScaler del sistema
                Text(
                  'Este texto respeta las preferencias de fuente del usuario.',
                  style: Theme.of(context).textTheme.bodyLarge,
                ),
                // Solo limitar la escala cuando sea absolutamente necesario
                Text(
                  'Texto con escala limitada a 1.5x (caso excepcional)',
                  style: Theme.of(context).textTheme.bodyMedium,
                  textScaler: TextScaler.linear(textScale.clamp(0.8, 1.5)),
                ),
              ],
            );
          }),
        ],
      ),
    );
  }
}

// ── Widget auxiliar: campo de texto con focus order ────────────────────────────
class _FocusableField extends StatelessWidget {
  final int order;
  final String label;
  final String hint;
  final bool obscure;

  const _FocusableField({
    required this.order,
    required this.label,
    required this.hint,
    this.obscure = false,
  });

  @override
  Widget build(BuildContext context) {
    return FocusTraversalOrder(
      order: NumericFocusOrder(order.toDouble()),
      child: Semantics(
        label: label,
        hint: hint,
        textField: true,
        child: TextField(
          obscureText: obscure,
          decoration: InputDecoration(
            labelText: label,
            hintText: hint,
            border: const OutlineInputBorder(),
          ),
        ),
      ),
    );
  }
}

// ── Título de sección ──────────────────────────────────────────────────────────
class _SectionTitle extends StatelessWidget {
  final String text;
  const _SectionTitle(this.text);
  @override
  Widget build(BuildContext context) => Text(
        text,
        style: Theme.of(context)
            .textTheme
            .titleSmall
            ?.copyWith(color: Theme.of(context).colorScheme.primary),
      );
}

Checklist de accesibilidad en Flutter

AspectoWidget / Práctica
Imagen descriptivaSemantics(label: '...', image: true)
Botón con estadoSemantics(button: true, checked: bool)
Agrupar elementosMergeSemantics
Ocultar decoracionesExcludeSemantics
Valor legible en sliderSemantics(value: '50 por ciento')
Orden de focoFocusTraversalGroup + OrderedTraversalPolicy
Fuente adaptableRespetar MediaQuery.textScalerOf(context)
Contraste≥ 4.5:1 para texto normal (WCAG AA)

Errores frecuentes

  • No usar label en imágenes: los lectores de pantalla anuncian “imagen” sin contexto. Siempre añade Semantics(label: '...', image: true) a imágenes que aportan información.
  • Botones con solo icono sin etiqueta: IconButton sin tooltip es ilegible para TalkBack. Añade tooltip o envuelve en Semantics(label: '...').
  • Limitar textScaleFactor sin necesidad: bloquear la escala de fuente es una barrera de accesibilidad. Solo hazlo en casos extremos y siempre permite al menos 1.3x.

Aplicación práctica

La accesibilidad es obligatoria en apps gubernamentales, bancarias y de salud en la UE y EEUU. Puedes verificar tu app con el Accessibility Inspector (iOS) o el TalkBack de Android. Flutter DevTools incluye el panel de semántica.

Siguiente ejercicio recomendado

Práctica guiada y siguiente paso

FAQ

¿Cómo pruebo la accesibilidad sin un dispositivo real?

En Android puedes activar TalkBack en el emulador. En iOS, activa VoiceOver en el simulador con Cmd+F5. Flutter DevTools también muestra el árbol semántico en la pestaña Widget Inspector.

¿Semantics afecta al rendimiento?

El impacto es mínimo. El árbol semántico solo se calcula cuando hay un servicio de accesibilidad activo en el dispositivo. No afecta el rendimiento en uso normal.

¿WCAG se aplica a apps móviles?

Las directrices WCAG 2.1 son extensibles a apps móviles y son la base de estándares como EN 301 549 (Europa) y Section 508 (EEUU). El criterio más relevante es el contraste de color (4.5:1 para texto normal) y el tamaño mínimo de área táctil (44×44 dp).