Cámara en Flutter: ejercicio resuelto con el plugin camera

Cámara en Flutter: ejercicio resuelto con el plugin camera

El plugin camera proporciona acceso de bajo nivel al hardware de la cámara: previsualización en tiempo real, captura de fotos, modos de flash, zoom y selección de cámara. Es la base sobre la que se construyen escáneres QR, apps de selfie y videollamadas.

Enunciado

Implementa una pantalla de cámara que:

  • Muestre la previsualización en tiempo real con CameraPreview.
  • Permita cambiar entre cámara frontal y trasera.
  • Capture una foto y la muestre en una galería de miniaturas.
  • Controle el modo de flash (auto, encendido, apagado).
  • Maneje correctamente el ciclo de vida del CameraController.

Dependencias

1
2
3
4
dependencies:
  camera: ^0.11.0+2
  path_provider: ^2.1.4
  path: ^1.9.0

Configuración Android

En android/app/build.gradle:

1
2
3
4
5
android {
    defaultConfig {
        minSdkVersion 21
    }
}

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

1
<uses-permission android:name="android.permission.CAMERA"/>

Configuración iOS

En ios/Runner/Info.plist:

1
2
3
4
<key>NSCameraUsageDescription</key>
<string>Necesitamos acceso a la cámara para tomar fotos</string>
<key>NSMicrophoneUsageDescription</key>
<string>Necesitamos el micrófono para grabar vídeo</string>

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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

// ── Entrada de la app ──────────────────────────────────────────────────────────
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final cameras = await availableCameras();
  runApp(MaterialApp(home: CameraScreen(cameras: cameras)));
}

// ── Pantalla principal de cámara ───────────────────────────────────────────────
class CameraScreen extends StatefulWidget {
  final List<CameraDescription> cameras;
  const CameraScreen({super.key, required this.cameras});

  @override
  State<CameraScreen> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen>
    with WidgetsBindingObserver {
  CameraController? _controller;
  int _cameraIndex = 0; // 0 = trasera, 1 = frontal (si existe)
  FlashMode _flashMode = FlashMode.auto;
  bool _isCapturing = false;
  final List<String> _capturedPaths = [];
  String? _initError;

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

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

  // Pausar/reanudar la cámara con el ciclo de vida de la app
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final ctrl = _controller;
    if (ctrl == null || !ctrl.value.isInitialized) return;

    if (state == AppLifecycleState.inactive) {
      ctrl.dispose();
    } else if (state == AppLifecycleState.resumed) {
      _initCamera();
    }
  }

  Future<void> _initCamera() async {
    if (widget.cameras.isEmpty) {
      setState(() => _initError = 'No se encontraron cámaras en este dispositivo.');
      return;
    }

    final camera = widget.cameras[_cameraIndex];
    final ctrl = CameraController(
      camera,
      ResolutionPreset.high,
      enableAudio: false,
      imageFormatGroup: ImageFormatGroup.jpeg,
    );

    try {
      await ctrl.initialize();
      await ctrl.setFlashMode(_flashMode);
      if (!mounted) return;
      setState(() {
        _controller = ctrl;
        _initError = null;
      });
    } on CameraException catch (e) {
      setState(() => _initError = '${e.code}: ${e.description}');
    }
  }

  Future<void> _switchCamera() async {
    if (widget.cameras.length < 2) return;
    await _controller?.dispose();
    setState(() {
      _cameraIndex = (_cameraIndex + 1) % widget.cameras.length;
      _controller = null;
    });
    await _initCamera();
  }

  Future<void> _cycleFlash() async {
    final modes = [FlashMode.auto, FlashMode.always, FlashMode.off, FlashMode.torch];
    final nextIndex = (modes.indexOf(_flashMode) + 1) % modes.length;
    final next = modes[nextIndex];
    await _controller?.setFlashMode(next);
    setState(() => _flashMode = next);
  }

  Future<void> _takePicture() async {
    final ctrl = _controller;
    if (ctrl == null || !ctrl.value.isInitialized || _isCapturing) return;

    setState(() => _isCapturing = true);

    try {
      final dir = await getTemporaryDirectory();
      final path = p.join(dir.path, '${DateTime.now().millisecondsSinceEpoch}.jpg');

      final file = await ctrl.takePicture();
      await File(file.path).copy(path);

      setState(() => _capturedPaths.insert(0, path));
    } on CameraException catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error al capturar: ${e.description}')),
        );
      }
    } finally {
      setState(() => _isCapturing = false);
    }
  }

  IconData get _flashIcon => switch (_flashMode) {
        FlashMode.auto => Icons.flash_auto,
        FlashMode.always => Icons.flash_on,
        FlashMode.off => Icons.flash_off,
        FlashMode.torch => Icons.highlight,
        _ => Icons.flash_auto,
      };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // ── Barra superior ───────────────────────────────────────────
            _TopBar(
              flashIcon: _flashIcon,
              onFlash: _cycleFlash,
              canSwitch: widget.cameras.length > 1,
              onSwitch: _switchCamera,
            ),

            // ── Previsualización ─────────────────────────────────────────
            Expanded(child: _buildPreview()),

            // ── Controles inferiores ─────────────────────────────────────
            _BottomControls(
              isCapturing: _isCapturing,
              onCapture: _takePicture,
              lastCapturePath: _capturedPaths.isNotEmpty ? _capturedPaths.first : null,
              onShowGallery: _capturedPaths.isEmpty
                  ? null
                  : () => _showGallery(context),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPreview() {
    if (_initError != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Text(
            _initError!,
            style: const TextStyle(color: Colors.red),
            textAlign: TextAlign.center,
          ),
        ),
      );
    }

    final ctrl = _controller;
    if (ctrl == null || !ctrl.value.isInitialized) {
      return const Center(child: CircularProgressIndicator(color: Colors.white));
    }

    return ClipRect(
      child: OverflowBox(
        alignment: Alignment.center,
        child: FittedBox(
          fit: BoxFit.cover,
          child: SizedBox(
            width: ctrl.value.previewSize?.height ?? 1,
            height: ctrl.value.previewSize?.width ?? 1,
            child: CameraPreview(ctrl),
          ),
        ),
      ),
    );
  }

  void _showGallery(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => _GalleryScreen(paths: List.from(_capturedPaths)),
      ),
    );
  }
}

// ── Barra superior ─────────────────────────────────────────────────────────────
class _TopBar extends StatelessWidget {
  final IconData flashIcon;
  final VoidCallback onFlash;
  final bool canSwitch;
  final VoidCallback onSwitch;

  const _TopBar({
    required this.flashIcon,
    required this.onFlash,
    required this.canSwitch,
    required this.onSwitch,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
            icon: Icon(flashIcon, color: Colors.white),
            onPressed: onFlash,
            tooltip: 'Cambiar flash',
          ),
          if (canSwitch)
            IconButton(
              icon: const Icon(Icons.flip_camera_ios, color: Colors.white),
              onPressed: onSwitch,
              tooltip: 'Cambiar cámara',
            ),
        ],
      ),
    );
  }
}

// ── Controles inferiores ───────────────────────────────────────────────────────
class _BottomControls extends StatelessWidget {
  final bool isCapturing;
  final VoidCallback onCapture;
  final String? lastCapturePath;
  final VoidCallback? onShowGallery;

  const _BottomControls({
    required this.isCapturing,
    required this.onCapture,
    this.lastCapturePath,
    this.onShowGallery,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          // Miniatura de última captura → galería
          GestureDetector(
            onTap: onShowGallery,
            child: Container(
              width: 56,
              height: 56,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.white54),
                color: Colors.white12,
              ),
              child: lastCapturePath != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(7),
                      child: Image.file(File(lastCapturePath!), fit: BoxFit.cover),
                    )
                  : const Icon(Icons.photo_library, color: Colors.white54),
            ),
          ),

          // Botón de captura
          GestureDetector(
            onTap: isCapturing ? null : onCapture,
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 150),
              width: isCapturing ? 64 : 72,
              height: isCapturing ? 64 : 72,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
                border: Border.all(color: Colors.white54, width: 4),
              ),
              child: isCapturing
                  ? const Padding(
                      padding: EdgeInsets.all(16),
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const SizedBox.shrink(),
            ),
          ),

          // Placeholder para centrar el botón de captura
          const SizedBox(width: 56),
        ],
      ),
    );
  }
}

// ── Galería de capturas ────────────────────────────────────────────────────────
class _GalleryScreen extends StatefulWidget {
  final List<String> paths;
  const _GalleryScreen({required this.paths});
  @override
  State<_GalleryScreen> createState() => _GalleryScreenState();
}

class _GalleryScreenState extends State<_GalleryScreen> {
  late final List<String> _paths = List.from(widget.paths);

  void _delete(String path) {
    File(path).deleteSync();
    setState(() => _paths.remove(path));
    if (_paths.isEmpty && mounted) Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Galería (${_paths.length})'),
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
      ),
      backgroundColor: Colors.black,
      body: GridView.builder(
        padding: const EdgeInsets.all(4),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 4,
          mainAxisSpacing: 4,
        ),
        itemCount: _paths.length,
        itemBuilder: (_, i) {
          final path = _paths[i];
          return GestureDetector(
            onTap: () => Navigator.of(context).push(
              MaterialPageRoute(
                builder: (_) => _PhotoViewer(path: path, onDelete: () => _delete(path)),
              ),
            ),
            child: Image.file(File(path), fit: BoxFit.cover),
          );
        },
      ),
    );
  }
}

class _PhotoViewer extends StatelessWidget {
  final String path;
  final VoidCallback onDelete;
  const _PhotoViewer({required this.path, required this.onDelete});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.delete, color: Colors.red),
            onPressed: () {
              onDelete();
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
      body: Center(child: Image.file(File(path))),
    );
  }
}

Métodos principales de CameraController

MétodoDescripción
initialize()Inicializa el hardware. Obligatorio antes de cualquier operación
takePicture()Captura una foto como XFile
startVideoRecording()Inicia la grabación de vídeo
stopVideoRecording()Detiene y devuelve el vídeo como XFile
setFlashMode(mode)Cambia el modo de flash
setZoomLevel(zoom)Ajusta el zoom (entre minZoomLevel y maxZoomLevel)
setFocusPoint(offset)Fija el punto de enfoque en coordenadas normalizadas (0,0)–(1,1)
setExposureOffset(value)Ajusta la exposición en EV

Errores frecuentes

  • No llamar dispose() al salir de la pantalla: CameraController mantiene un stream activo del sensor. Si no haces dispose(), el indicador de cámara en iOS/Android sigue activo y la siguiente apertura falla.
  • No gestionar WidgetsBindingObserver: cuando la app pasa a segundo plano, el acceso a la cámara puede ser revocado por el sistema. Escucha didChangeAppLifecycleState para hacer dispose en inactive y reiniciar en resumed.
  • Usar XFile.path directamente como ruta permanente: takePicture() guarda en una carpeta temporal que el OS puede limpiar. Copia el archivo a getApplicationDocumentsDirectory() si necesitas persistencia.

Aplicación práctica

La cámara es la base de: escáneres QR/barcode (con mobile_scanner), apps de documentos (escaneo + OCR), filtros de realidad aumentada, y verificación de identidad (KYC) en apps fintech.

Siguiente ejercicio recomendado

Práctica guiada y siguiente paso

FAQ

¿Puedo usar el plugin camera en el emulador de Android?

Sí, pero la previsualización mostrará una escena de prueba generada, no la cámara real. Para probar captura real necesitas un dispositivo físico.

¿Por qué hay que usar ResolutionPreset.high y no max?

ResolutionPreset.max puede causar problemas de rendimiento en dispositivos de gama baja y aumentar considerablemente el tiempo de inicialización. high ofrece un buen equilibrio entre calidad y rendimiento.

¿El plugin camera soporta escaneo de QR?

No directamente. Para escanear QR y códigos de barras usa el plugin mobile_scanner o qr_code_scanner, que están optimizados para procesamiento continuo de frames y reconocimiento de patrones.