Sub topic 14
Flash, zoom, and switching cameras
This chapter assumes you can already create, initialize, and dispose a CameraController, show a CameraPreview, and call takePicture. Here you add three controls on top of that: flash, zoom, and a front/back camera switch. Each looks like a single method call. Each also has device-dependent behavior you need to handle.
Flash modes
CameraController.setFlashMode takes a FlashMode value. The same setting applies to photos taken afterwards, and torch also affects the live preview.
| Mode | Effect |
|---|---|
| `FlashMode.off` | The flash never fires. |
| `FlashMode.auto` | The device decides at capture time, based on scene brightness. |
| `FlashMode.always` | The flash fires on every `takePicture`. |
| `FlashMode.torch` | The light stays on continuously, which is useful for video or as a flashlight. |
The enum declares the modes in the order above, so a "tap to cycle" button can step through FlashMode.values.
Some limits apply:
- Most front cameras have no flash hardware. Calling
setFlashModeon them may throw aCameraExceptionor may do nothing, depending on the platform and device. Treat the call as fallible, and keep the UI in sync only after it succeeds. - A new controller does not always start in the mode you expect. Call
setFlashMode(FlashMode.off)afterinitializeso the UI and the camera agree. - Flash state belongs to the controller. When you replace the controller (for example when switching cameras), the flash state is lost, and you must reset your UI state with it.
Zoom
Zoom has three calls:
getMinZoomLevel()returns the smallest supported zoom, usually1.0.getMaxZoomLevel()returns the largest zoom the device reports. It varies a lot between devices.setZoomLevel(double)applies a zoom level. A value outside the min/max range throws aCameraException, so clamp the value before you call it.
Read the limits once, right after initialize, and store them. They are different for each camera, so read them again whenever you switch cameras.
setZoomLevel is asynchronous and crosses a platform channel. A slider or pinch gesture can fire it many times a second. The calls are processed in order, so rapid input can queue up work and make the preview feel laggy. The simplest guard is to skip a new call while the previous one is still running. The pinch example further down shows this.
Switching cameras
A CameraController is built for one CameraDescription. Switching between front and back therefore means closing the current controller and opening a new one. Recent versions of the plugin also offer setDescription, which does the swap for you, but check that your pinned camera version has it. Creating a new controller works on every version.
The steps for the new-controller approach are:
- Remove the controller from the widget tree, so no
CameraPreviewis still reading it. - Wait for that frame to finish, then dispose the old controller.
- Pick the other
CameraDescriptionby comparinglensDirection. - Create and initialize a new controller, then read its zoom limits and reset flash.
- Put the new controller back into state.
Step 1 matters. If you dispose a controller while a CameraPreview for it is still on screen, the next build can throw because the controller is already disposed.
A complete screen
This screen combines all three controls. It follows the lifecycle rules from earlier chapters: it disposes the controller in dispose and checks mounted after every await. For brevity it leaves out the WidgetsBindingObserver handling from the lifecycle chapter. Add that to any production screen.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class CameraToolsScreen extends StatefulWidget {
const CameraToolsScreen({super.key});
@override
State<CameraToolsScreen> createState() => _CameraToolsScreenState();
}
class _CameraToolsScreenState extends State<CameraToolsScreen> {
List<CameraDescription> _cameras = [];
CameraController? _controller;
FlashMode _flashMode = FlashMode.off;
double _minZoom = 1.0;
double _maxZoom = 1.0;
double _zoom = 1.0;
bool _busy = false;
String? _error;
@override
void initState() {
super.initState();
_start();
}
Future<void> _start() async {
try {
_cameras = await availableCameras();
} on CameraException catch (e) {
if (mounted) setState(() => _error = e.description ?? e.code);
return;
}
if (!mounted) return;
if (_cameras.isEmpty) {
setState(() => _error = 'No cameras found');
return;
}
await _open(_cameras.first);
}
Future<void> _open(CameraDescription description) async {
final old = _controller;
if (old != null) {
// Take the old controller out of the tree before disposing it.
setState(() => _controller = null);
await WidgetsBinding.instance.endOfFrame;
await old.dispose();
}
final next = CameraController(
description,
ResolutionPreset.medium,
enableAudio: false,
);
try {
await next.initialize();
final min = await next.getMinZoomLevel();
final max = await next.getMaxZoomLevel();
try {
await next.setFlashMode(FlashMode.off);
} on CameraException {
// Some cameras have no flash. Ignore and carry on.
}
if (!mounted) {
await next.dispose();
return;
}
setState(() {
_controller = next;
_flashMode = FlashMode.off;
_minZoom = min;
_maxZoom = max;
_zoom = min;
_error = null;
});
} on CameraException catch (e) {
await next.dispose();
if (mounted) setState(() => _error = e.description ?? e.code);
}
}
Future<void> _cycleFlash() async {
final controller = _controller;
if (controller == null) return;
const modes = FlashMode.values;
final next = modes[(modes.indexOf(_flashMode) + 1) % modes.length];
try {
await controller.setFlashMode(next);
if (mounted) setState(() => _flashMode = next);
} on CameraException catch (e) {
debugPrint('Flash not available: ${e.code}');
}
}
Future<void> _setZoom(double value) async {
final controller = _controller;
if (controller == null || _busy) return;
_busy = true;
setState(() => _zoom = value);
try {
await controller.setZoomLevel(value);
} on CameraException catch (e) {
debugPrint('Zoom failed: ${e.code}');
} finally {
_busy = false;
}
}
Future<void> _switchCamera() async {
final controller = _controller;
if (controller == null || _cameras.length < 2) return;
final current = controller.description.lensDirection;
final target = _cameras.firstWhere(
(d) => d.lensDirection != current,
orElse: () => controller.description,
);
await _open(target);
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_error != null) {
return Scaffold(body: Center(child: Text(_error!)));
}
final controller = _controller;
if (controller == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
CameraPreview(controller),
Positioned(
left: 16,
right: 16,
bottom: 32,
child: Row(
children: [
IconButton(
color: Colors.white,
onPressed: _cycleFlash,
icon: Icon(switch (_flashMode) {
FlashMode.off => Icons.flash_off,
FlashMode.auto => Icons.flash_auto,
FlashMode.always => Icons.flash_on,
FlashMode.torch => Icons.highlight,
}),
),
Expanded(
child: Slider(
min: _minZoom,
max: _maxZoom,
value: _zoom.clamp(_minZoom, _maxZoom),
onChanged: _maxZoom > _minZoom ? _setZoom : null,
),
),
IconButton(
color: Colors.white,
onPressed: _cameras.length > 1 ? _switchCamera : null,
icon: const Icon(Icons.cameraswitch),
),
],
),
),
],
),
);
}
}A few details in this code are easy to miss:
_openhandles both the first start and every later switch. During a switch,_controllerisnullfor a moment, so the build method shows a spinner instead of a stale preview.- The
SliderreceivesnullforonChangedwhen the camera cannot zoom (_maxZoom == _minZoom). That disables it. _zoom.clamp(_minZoom, _maxZoom)keeps the slider value in range after a switch, because the two cameras can have different limits. Theclampcall returnsnum, so on newer Dart versions you may need.toDouble()to satisfy theSlidertype.
Pinch to zoom
Most camera apps zoom with a pinch gesture. Wrap the preview in a GestureDetector. Remember the zoom level when the gesture starts, then multiply it by the gesture's scale factor on every update.
double _baseZoom = 1.0;
Widget pinchZoomPreview(CameraController controller) {
return GestureDetector(
onScaleStart: (_) => _baseZoom = _zoom,
onScaleUpdate: (details) {
final target = (_baseZoom * details.scale).clamp(_minZoom, _maxZoom);
_setZoom(target.toDouble());
},
child: CameraPreview(controller),
);
}Place this method and the _baseZoom field in the _CameraToolsScreenState class above, and use pinchZoomPreview(controller) in place of the plain CameraPreview(controller). The _busy flag in _setZoom drops updates that arrive while a call is still pending. That keeps the preview responsive, and the next update carries the latest scale anyway.
Common errors
- Zoom value out of range. A level below the minimum or above the maximum throws. Always clamp, and re-read the limits after a camera switch.
- Using a disposed controller. Fast taps on the switch button can start a second
_openwhile the first is still running. Guard with a busy flag, or disable the button until the switch finishes. The screen above avoids most of this because the button does nothing useful while_controllerisnull, but a production screen should use an explicit flag. - Assuming a flash exists. Check for a
CameraExceptioninstead of checking the camera direction. Back cameras on some devices and emulators also lack a flash. - Stale UI state. The flash icon and zoom slider describe the controller, not the screen. Reset them whenever you create a new controller.
- Only two cameras. Many phones list more than two entries in
availableCameras(), such as wide and ultra-wide lenses. Matching onlensDirectionpicks the first match. If you want a specific lens, let the user choose from the list instead.
Exercise
A user taps the camera switch button, and your app throws an error saying the camera controller was used after it was disposed. What ordering mistake in the switching code most likely causes this, and how do you fix it?
Show answer
The old controller was disposed while a CameraPreview that reads it was still in the widget tree, so the next build touched a disposed controller. Fix it by first setting the controller field to null (and showing a placeholder), waiting for that frame to finish with WidgetsBinding.instance.endOfFrame, and only then calling dispose on the old controller before creating and initializing the new one.
Exercise
Your zoom slider works on the back camera. After switching to the front camera, calling setZoomLevel with the slider's last value throws a CameraException. Give the cause and two changes that prevent it.
Show answer
The front camera has a different zoom range, and the old value is outside it. Re-read getMinZoomLevel and getMaxZoomLevel after initializing the new controller and store them, and reset the zoom state to the new minimum. Also clamp any value to the stored min and max before calling setZoomLevel.