Sub topic 10
Displaying the live preview
This chapter covers how to show the camera's live feed inside your own widget tree with CameraPreview. It assumes you can already list cameras and create and initialize a CameraController, which the previous chapters covered. You should also be comfortable with StatefulWidget lifecycle methods and FutureBuilder.
What CameraPreview does
CameraPreview is a widget from the camera package. It takes an initialized CameraController and draws the frames the camera produces. On Android it renders into a Texture widget. On iOS it does the same through a texture that the plugin registers with the Flutter engine. Because the preview is an ordinary widget, you can size it, clip it, rotate it, and stack other widgets on top of it.
The widget has one required argument and one optional one:
controller: theCameraControllerwhose frames are displayed.child: an optional widget drawn on top of the preview. It is placed in the same rotated box as the preview, so it is a convenient place for overlays that must line up with the image, such as a framing guide.
CameraPreview(controller, child: const FramingGuide())The preview does not own the controller. Disposing of the CameraPreview widget does not stop the camera. You must call controller.dispose() yourself, as the lifecycle chapter describes.
The initialization rule
CameraPreview reads controller.value when it builds. If the controller has not finished initialize(), there is no texture to show. In current versions of the plugin, the widget returns an empty Container when the controller is not initialized. In older versions, it could throw. Either way, you should never build it before initialization completes.
The standard pattern is to start initialization once in initState, keep the resulting Future, and gate the preview behind a FutureBuilder.
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> _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 matter here.
- The
Futureis stored in a field. If you called_setup()insidebuild, every rebuild would create a new controller and open the camera again. - The controller is assigned to
_controllerbeforeinitialize()is awaited. This letsdisposerelease it even when initialization is still running or has failed. - The
hasErrorbranch is where permission denial and device failures end up. The error-handling chapter covers it in detail.
Sizing and aspect ratio
CameraPreview wraps an AspectRatio internally, using the value from controller.value.aspectRatio. This is the ratio of the sensor output after rotation for the current device orientation. The widget will take the largest size that fits its constraints while keeping that ratio. Inside a Scaffold body, that usually means the preview is letterboxed: it fills the width on a phone in portrait and leaves bars above and below.
That behavior is correct but is often not what a camera screen should look like. Two common alternatives are described below.
Filling the screen by cropping
To fill the whole screen, scale the preview so it covers the available space and let the overflow be clipped. This is the same idea as BoxFit.cover for images.
Widget fullScreenPreview(BuildContext context, CameraController controller) {
final size = MediaQuery.sizeOf(context);
final screenRatio = size.width / size.height;
final previewRatio = controller.value.aspectRatio;
// Scale up so the preview covers the screen in both dimensions.
var scale = screenRatio * previewRatio;
if (scale < 1) scale = 1 / scale;
return ClipRect(
child: Transform.scale(
scale: scale,
child: Center(child: CameraPreview(controller)),
),
);
}The cropped edges are still part of the captured photo. The user sees less than the camera records, so a full-screen preview can surprise people when they open the saved picture. If the final image must match what the user sees, either keep the preview letterboxed or crop the file after capture.
Fixing the preview to a shape
For a square or other fixed shape, constrain the preview with AspectRatio and ClipRRect, and fill that box using FittedBox with BoxFit.cover. CameraPreview reports its size through controller.value.previewSize, which you can pass to a SizedBox inside the FittedBox.
Widget squarePreview(CameraController controller) {
final previewSize = controller.value.previewSize!;
return AspectRatio(
aspectRatio: 1,
child: ClipRect(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
// previewSize is in sensor orientation (landscape), so swap
// width and height for a portrait phone.
width: previewSize.height,
height: previewSize.width,
child: CameraPreview(controller),
),
),
),
);
}The swap of width and height is a common source of confusion. previewSize is reported in the sensor's native landscape orientation on Android. On a portrait device, the visible image is rotated, so its width is the reported height. Test on both a phone and a tablet before you rely on this.
Orientation
The preview rotates to match the device orientation without any code from you, and controller.value.aspectRatio changes with it. This works through RotatedBox and NativeDeviceOrientationListener-style handling inside the plugin. When your layout rebuilds on rotation, the MediaQuery size changes too, so any full-screen math like the example above stays correct as long as you compute it inside build.
If your app locks orientation with SystemChrome.setPreferredOrientations, the preview follows the locked orientation. The captured file may still carry EXIF orientation metadata that differs from what you expect. Check a saved photo on a device rather than assuming the preview and file match.
callout noteThe previous block is not a valid callout. The correct form is shown next.
Overlays and rebuilds
A camera screen usually has buttons, a flash toggle, and a grid over the preview. Use a Stack and keep the preview at the bottom:
Widget cameraStack(CameraController controller, VoidCallback onCapture) {
return Stack(
fit: StackFit.expand,
children: [
Center(child: CameraPreview(controller)),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 32),
child: FloatingActionButton(
onPressed: onCapture,
child: const Icon(Icons.camera_alt),
),
),
),
],
);
}CameraController is a ValueNotifier<CameraValue>. Its value changes when a picture is taken, when recording starts, or when the flash mode changes. If you want a widget to react to those changes, wrap it in a ValueListenableBuilder instead of calling setState for the whole screen:
ValueListenableBuilder<CameraValue>(
valueListenable: controller,
builder: (context, value, _) {
return Icon(
value.isTakingPicture ? Icons.hourglass_top : Icons.camera_alt,
);
},
)This keeps rebuilds local. The Texture that CameraPreview draws is updated by the platform, not by Flutter's build phase, so the video does not need a rebuild to show new frames.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Black screen, no error | Preview built before `initialize()` completed, or the controller was disposed | Gate the preview on the init future and check `value.isInitialized` |
| Red error screen about a disposed controller | `dispose()` ran, but a widget still builds `CameraPreview` | Set the controller to null or rebuild without the preview after disposal |
| Stretched preview | Wrapping `CameraPreview` in a fixed `SizedBox` with a different ratio | Use `AspectRatio`, or the `FittedBox` approach above |
| Preview rotated by 90 degrees on a tablet | Hard-coded width and height swap | Derive orientation from `MediaQuery` or `value.deviceOrientation` |
| Preview freezes after returning from the background | Controller was not recreated after the app resumed | Follow the lifecycle pattern from the next chapter |
| Camera in use by another app | A second controller is open, or the previous one was not disposed | Dispose the old controller before creating a new one |
A flow to keep in mind
Exercises
Exercise
Why should _initFuture be created in initState and not inside build?
Show answer
build can run many times, for example on rotation or when a parent rebuilds. Creating the future there would build a new CameraController and open the camera again on each call. Creating it once in initState and storing it keeps a single controller for the life of the screen.
Exercise
A full-screen preview built with Transform.scale looks right, but saved photos show more of the scene than the user saw. Why, and what are two ways to handle it?
Show answer
The scale only crops what is drawn on screen. The camera still captures the full sensor frame. You can keep the preview letterboxed so it matches the photo, or crop the saved file to the visible region after capture.