Sub topic 10
Displaying the Live Camera Preview
This chapter assumes you know Dart async and await, Flutter StatefulWidget lifecycle methods, and how to add packages in pubspec.yaml. It also assumes that a CameraController has been created and initialized, as described in the previous chapter.
A live preview is the widget that displays frames from the selected camera. Flutter's camera package provides this widget as CameraPreview. It must receive an initialized CameraController.
The preview depends on initialization
Camera setup is asynchronous because Flutter must discover the hardware, request access, and configure the camera. Do not build CameraPreview before initialize() completes. The controller may exist while its camera is still unavailable.
A FutureBuilder is a convenient way to display loading, error, and preview states:
flowchart TD
A[Create CameraController] --> B[Call initialize]
B -->|waiting| C[Show progress indicator]
B -->|error| D[Show camera unavailable]
B -->|success| E[Show CameraPreview]Build a preview screen
The following screen starts camera initialization in initState(). The FutureBuilder rebuilds when that future changes state.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class PreviewScreen extends StatefulWidget {
const PreviewScreen({super.key});
@override
State<PreviewScreen> createState() => _PreviewScreenState();
}
class _PreviewScreenState extends State<PreviewScreen> {
CameraController? _controller;
late final Future<void> _initialization;
@override
void initState() {
super.initState();
_initialization = _initializeCamera();
}
Future<void> _initializeCamera() async {
final cameras = await availableCameras();
if (cameras.isEmpty) {
throw CameraException(
'NoCamera',
'This device has no available camera.',
);
}
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(
appBar: AppBar(title: const Text('Camera preview')),
body: FutureBuilder<void>(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError || _controller == null) {
return const Center(
child: Text('The camera is unavailable.'),
);
}
return Center(
child: AspectRatio(
aspectRatio: _controller!.value.aspectRatio,
child: CameraPreview(_controller!),
),
);
},
),
);
}
}AspectRatio keeps the preview proportional to the camera sensor. Without it, placing the preview in a widget with unrelated dimensions can stretch or crop the image.
The enableAudio: false option is appropriate for a photo-only preview. Set it to true when the same controller will record video with sound, and make sure the platform microphone permission is configured.
Common preview errors
- Showing
CameraPreviewbefore initialization finishes can cause an assertion or an invalid preview. - Calling
availableCameras()on every rebuild can repeatedly query the platform. Start it frominitState(). - Forgetting
dispose()can leave the camera occupied after leaving the screen. - Assuming
cameras.firstis always the rear camera is unsafe. Later, select a camera by itslensDirection.
Exercise
Why should CameraPreview be built only after the initialization future completes?
Show answer
The widget needs a controller whose native camera session has finished initializing; otherwise the preview has no ready camera stream.