Camera in Flutter: solved exercise with the camera plugin

Camera in Flutter: solved exercise with the camera plugin

The camera plugin provides low-level access to camera hardware: real-time preview, photo capture, flash modes, zoom, and camera selection. It is the foundation for QR scanners, selfie apps, and video calls.

Problem statement

Build a camera screen that:

  • Shows a real-time preview with CameraPreview.
  • Allows switching between front and rear cameras.
  • Captures a photo and displays it in a thumbnail gallery.
  • Controls flash mode (auto, on, off, torch).
  • Correctly handles the CameraController lifecycle.

Dependencies

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

Android setup

In android/app/build.gradle:

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

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

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

iOS setup

In ios/Runner/Info.plist:

1
2
3
4
<key>NSCameraUsageDescription</key>
<string>We need camera access to take photos</string>
<key>NSMicrophoneUsageDescription</key>
<string>We need the microphone to record video</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
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';

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

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;
  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();
  }

  @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 cameras found on this device.');
      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 next = modes[(modes.indexOf(_flashMode) + 1) % modes.length];
    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('Capture error: ${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: [
            _TopBar(
              flashIcon: _flashIcon,
              onFlash: _cycleFlash,
              canSwitch: widget.cameras.length > 1,
              onSwitch: _switchCamera,
            ),
            Expanded(child: _buildPreview()),
            _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)),
    ));
  }
}

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: 'Toggle flash'),
          if (canSwitch)
            IconButton(icon: const Icon(Icons.flip_camera_ios, color: Colors.white), onPressed: onSwitch, tooltip: 'Switch camera'),
        ],
      ),
    );
  }
}

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: [
          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),
            ),
          ),
          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(),
            ),
          ),
          const SizedBox(width: 56),
        ],
      ),
    );
  }
}

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('Gallery (${_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))),
    );
  }
}

Main CameraController methods

MethodDescription
initialize()Initializes the hardware. Required before any operation
takePicture()Captures a photo as XFile
startVideoRecording()Starts video recording
stopVideoRecording()Stops and returns the video as XFile
setFlashMode(mode)Changes flash mode
setZoomLevel(zoom)Adjusts zoom (between minZoomLevel and maxZoomLevel)
setFocusPoint(offset)Sets focus point in normalized coordinates (0,0)–(1,1)
setExposureOffset(value)Adjusts exposure in EV

Common mistakes

  • Not calling dispose() when leaving the screen: CameraController keeps an active sensor stream. If you don’t dispose(), the camera indicator on iOS/Android stays active and the next open fails.
  • Not handling WidgetsBindingObserver: when the app goes to the background, camera access may be revoked by the OS. Listen to didChangeAppLifecycleState to dispose on inactive and reinitialize on resumed.
  • Using XFile.path directly as a permanent path: takePicture() saves to a temporary folder that the OS may clean up. Copy the file to getApplicationDocumentsDirectory() if you need persistence.

Practical use

The camera is the foundation for: QR/barcode scanners (with mobile_scanner), document scanning apps (scan + OCR), augmented reality filters, and identity verification (KYC) in fintech apps.

Guided practice and next step

FAQ

Can I use the camera plugin on the Android emulator?

Yes, but the preview will show a generated test scene, not a real camera. For real capture testing you need a physical device.

Why use ResolutionPreset.high instead of max?

ResolutionPreset.max can cause performance issues on low-end devices and significantly increase initialization time. high offers a good balance between quality and performance.

Does the camera plugin support QR scanning?

Not directly. For QR codes and barcodes use the mobile_scanner or qr_code_scanner plugin, which are optimized for continuous frame processing and pattern recognition.