Sub topic 9
Initializing a CameraController
This chapter assumes you know Dart async and await, Future, and the StatefulWidget lifecycle. It also assumes the camera package is installed and that Android and iOS camera permissions are configured.
What the controller does
A CameraController connects your Flutter code to one physical camera. It manages the camera session, resolution, audio capture, preview stream, and later operations such as taking a picture or recording video.
Initialization is asynchronous because Flutter must ask the operating system for access and prepare the camera hardware. Do not show CameraPreview or call capture methods until initialization finishes.
The usual sequence is:
Discovering and initializing a camera
Call availableCameras() before creating the controller. It returns a list of CameraDescription objects. Each description identifies a camera, such as the rear or front camera.
This example selects the first camera and uses a medium resolution. Audio is disabled because this screen only takes photos.
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> _initializeFuture;
@override
void initState() {
super.initState();
_initializeFuture = _initializeCamera();
}
Future<void> _initializeCamera() async {
final cameras = await availableCameras();
if (cameras.isEmpty) {
throw StateError('No cameras are available');
}
final controller = CameraController(
cameras.first,
ResolutionPreset.medium,
enableAudio: false,
);
_controller = controller;
try {
await controller.initialize();
} on CameraException {
await controller.dispose();
_controller = null;
rethrow;
}
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initializeFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError || _controller == null) {
return const Center(child: Text('Camera unavailable'));
}
return CameraPreview(_controller!);
},
),
);
}
}FutureBuilder rebuilds when _initializeFuture changes state. While the future is pending, the screen displays a progress indicator. After success, _controller is initialized and safe to use. If initialization fails, the widget displays a fallback instead of trying to build an invalid preview.
ResolutionPreset controls the requested capture quality. Higher presets can produce larger images and use more memory. The operating system or device may provide a lower resolution than requested.
Common initialization errors
- Calling
CameraPreviewbeforeinitialize()completes can throw an error or display an invalid preview. - Calling
cameras.firstwithout checking the list can fail on devices with no usable camera. - Forgetting platform permission declarations can make
initialize()throw aCameraException. - Creating multiple controllers without disposing the old ones can leave the camera occupied.
The next step is to add capture controls after initialization has succeeded.
Exercise
Why does the example store the initialization future and pass it to FutureBuilder instead of calling initialize inside build?
Show answer
build can run many times. Starting initialization there could create repeated camera sessions. Starting it in initState runs it once for the widget, while FutureBuilder displays the correct loading, success, or error state.