Sub topic 9
Initializing a CameraController
This chapter covers how to create a CameraController, call initialize() correctly, and handle the failures that can happen on the way. It assumes you know async/await, the StatefulWidget lifecycle (initState, dispose), and that you have already added the camera package and declared platform permissions. The previous chapter showed how to list cameras with availableCameras(). Here you turn one entry from that list into a working controller.
What a CameraController is
A CameraController is the object that owns one connection to one physical camera. It does three jobs:
- It opens the camera hardware and negotiates a resolution and format.
- It holds the state of that connection in a
CameraValue(initialized, recording, errored, current zoom and flash mode, and so on). - It is the object you pass to
CameraPreviewand calltakePicture()on.
Creating the controller does not touch the hardware. The constructor only stores your settings. The camera opens, and the permission prompt appears, only when you call initialize(). Until that Future completes, the preview and capture methods are unusable.
The constructor parameters
The constructor takes a CameraDescription and a ResolutionPreset. Several named parameters are optional.
final controller = CameraController(
cameras.first,
ResolutionPreset.medium,
enableAudio: false,
);| Parameter | Purpose | Notes |
|---|---|---|
| `description` | Which camera to open | Taken from `availableCameras()` |
| `resolutionPreset` | Target quality for preview and capture | `low`, `medium`, `high`, `veryHigh`, `ultraHigh`, `max` |
| `enableAudio` | Whether to capture sound with video | Defaults to `true` |
| `imageFormatGroup` | Pixel format of image streams | Matters only if you process frames yourself |
Two parameters need extra attention.
resolutionPreset. Higher presets cost more memory, more battery, and more processing time per frame. They are also a request, not a guarantee. If a device cannot supply max, the plugin picks the closest resolution it supports. Start with medium for a typical photo screen and raise it only when you can show that you need the detail. Read the real size afterwards from controller.value.previewSize.
enableAudio. The default is true, and a controller with audio enabled asks for microphone permission during initialize(). If you only take photos, set enableAudio: false. Otherwise a user can be asked for a permission your feature never uses, and a user who denies it can make initialization fail. If you set it to true on iOS, NSMicrophoneUsageDescription must be in Info.plist.
Calling initialize()
initialize() returns a Future<void>. It completes when the camera is open and the preview texture is ready. During that time the platform may show a permission dialog, so the call can take as long as the user takes to answer.
Future<void> setup() async {
final cameras = await availableCameras();
final controller = CameraController(
cameras.first,
ResolutionPreset.medium,
enableAudio: false,
);
await controller.initialize();
}After it completes, controller.value.isInitialized is true. Before that, it is false, and calling takePicture() throws a CameraException.
You can also listen to the controller, since it is a ValueNotifier<CameraValue>. This is useful if you want to rebuild when the state changes, for example when an error is reported after initialization.
Wiring it into a StatefulWidget
The controller is a long-lived object with native resources behind it. It belongs in a State, created once in initState and released in dispose. Do not create it in build, because build can run many times and each run would open the camera again.
The usual pattern stores the initialization Future in a field and hands it to a FutureBuilder.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class CameraScreen extends StatefulWidget {
const CameraScreen({super.key});
@override
State<CameraScreen> createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
CameraController? _controller;
late final Future<void> _initFuture;
@override
void initState() {
super.initState();
_initFuture = _setup();
}
Future<void> _setup() async {
final cameras = await availableCameras();
final controller = CameraController(
cameras.first,
ResolutionPreset.medium,
enableAudio: false,
);
_controller = controller;
await controller.initialize();
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return const Center(child: Text('Camera unavailable'));
}
return CameraPreview(_controller!);
},
),
);
}
}Three details in this code are deliberate.
- The
_controllerfield is assigned beforeawait controller.initialize(). If initialization fails,dispose()still has a reference and can release whatever was acquired. - The
Futureis stored in_initFuturerather than created insidebuild. If you wrotefuture: _setup()inbuild, every rebuild would start a new initialization. - The
FutureBuildercheckssnapshot.hasErrorbefore showing the preview. Without that branch, a failed initialization would reachCameraPreviewwith an uninitialized controller.
The preview itself is covered in the next chapter. Here it is only the thing that proves initialization worked.
What happens when initialization fails
initialize() throws a CameraException when it cannot open the camera. The exception has a code string and a description. Common causes:
- The user denied camera permission. The code is typically
CameraAccessDenied, orCameraAccessDeniedWithoutPromptorCameraAccessRestrictedon iOS. - Audio was enabled and the user denied microphone permission (
AudioAccessDenied). - Another app or another controller already holds the camera.
- The device has no usable camera, such as an emulator without a configured virtual camera.
Wrap the call so the screen can show a fallback.
Future<void> safeInit(CameraController controller) async {
try {
await controller.initialize();
} on CameraException catch (e) {
debugPrint('Camera error ${e.code}: ${e.description}');
}
}This version logs and returns normally. If you use it inside _setup, the FutureBuilder will see a successful Future and show a preview for an uninitialized controller. Choose one of two designs. Either rethrow after logging so snapshot.hasError is true, or check controller.value.isInitialized in the builder before building CameraPreview. Rethrowing is simpler.
Error handling for permissions is treated in more depth in a later chapter. For now, the rule is that every initialize() call must be inside code that expects it to fail.
Common mistakes
- Initializing twice. Calling
initialize()on a controller that is already initialized throws. Create a new controller if you need different settings. - Using the controller after
dispose(). A disposed controller cannot be reused. Any call on it throws, andCameraPreviewfails to build. - Forgetting to await. Calling
takePicture()right afterinitialize()withoutawaitruns before the camera is ready. - Empty camera list.
cameras.firstthrows aStateErroron a device with no cameras. Checkcameras.isEmptyfirst if you target emulators or unusual hardware. - Calling
setStateafter dispose. If you update state afterawait controller.initialize(), checkmountedfirst, because the user may have left the screen during the permission dialog.
Summary of the sequence
- Get the cameras with
availableCameras(). - Check that the list is not empty.
- Construct a
CameraControllerwith a description and a modest resolution preset, and disable audio if you only take photos. - Store the controller in a field, then
await controller.initialize()inside a method called once frominitState. - Handle
CameraExceptionso failure produces a visible fallback. - Call
dispose()in theState'sdispose.
Exercise
A screen builds its FutureBuilder with future: _setup() written directly inside build, and users report that the camera flickers and sometimes fails with "camera already in use". What is wrong, and how do you fix it?
Show answer
Every rebuild calls _setup() again, which creates and initializes a new CameraController while earlier ones are still open, so the camera is opened repeatedly and conflicts with itself. Fix it by calling _setup() once in initState, storing the resulting Future in a field such as _initFuture, and passing that field to FutureBuilder. Also make sure the single controller is disposed in dispose().
Exercise
Your app only takes still photos, but users see a microphone permission prompt when the camera screen opens, and some who deny it get a failed initialization. Which constructor parameter do you change, and to what?
Show answer
Set enableAudio: false on the CameraController. With the default of true, initialize() requests microphone access even though photo capture does not need it.