Sub topic 3
Taking a picture
This chapter assumes you know async/await, StatefulWidget lifecycle methods (initState, dispose), and the camera plugin setup from the previous chapter. The code below works inside a State class that uses the camera package.
Taking a picture
A CameraController takes the photo. Call takePicture() and await the returned XFile, which holds the path to the saved image.
Future<void> _capture() async {
final XFile file = await _controller!.takePicture();
debugPrint('Saved to ${file.path}');
}Handling pause, resume, and disposal
Cameras are shared hardware. Release the controller when the app goes inactive, then create a new one on resume. The WidgetsBindingObserver mixin delivers these events.
class _CameraScreenState extends State<CameraScreen> with WidgetsBindingObserver {
CameraController? _controller;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_startCamera();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final controller = _controller;
if (controller == null || !controller.value.isInitialized) return;
if (state == AppLifecycleState.inactive) {
controller.dispose();
} else if (state == AppLifecycleState.resumed) {
_startCamera();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller?.dispose();
super.dispose();
}
}Handling denied permissions and errors
initialize() throws a CameraException when the user denies camera access or the device has no usable camera. Catch it and show a fallback, so the app does not crash.
Future<void> _startCamera() async {
try {
final cameras = await availableCameras();
final controller = CameraController(
cameras.first,
ResolutionPreset.medium,
enableAudio: false,
);
_controller = controller;
await controller.initialize();
if (mounted) setState(() {});
} on CameraException catch (e) {
debugPrint('Camera error ${e.code}: ${e.description}');
}
}> Note that availableCameras() can also throw on some devices, so keep the whole setup inside the try block.
Flash, zoom, and switching cameras
Set flash with setFlashMode, and clamp zoom to the range the hardware supports. To switch cameras, dispose the current controller and create one for a camera with a different lens direction.
Future<void> setupControls(CameraController c) async {
await c.setFlashMode(FlashMode.auto);
final min = await c.getMinZoomLevel();
final max = await c.getMaxZoomLevel();
await c.setZoomLevel(2.0.clamp(min, max));
}Recording video
Start and stop recording on the same controller. stopVideoRecording() returns an XFile for the saved video. Create the controller with enableAudio: true if the clip needs sound.
Future<void> startVideo() => _controller!.startVideoRecording();
Future<XFile> stopVideo() => _controller!.stopVideoRecording();Testing and verifying on real devices
Hide the plugin behind a small interface, so widget tests can inject a fake. Then verify the real behavior on hardware, because emulators do not reproduce camera permissions or lifecycle events accurately.
abstract class PhotoSource {
Future<String> capture();
}
class FakePhotoSource implements PhotoSource {
@override
Future<String> capture() async => '/tmp/fake.jpg';
}Exercise
Why does the controller get disposed on inactive instead of only on dispose()?
Show answer
Camera hardware is shared, and other apps need it while this app is in the background. Releasing it on inactive frees the camera, and resumed creates a new controller.