Sub topic 11
Taking a Picture
This chapter assumes that you know Dart async and await, Flutter StatefulWidget, and how to initialize a CameraController. It also assumes that the controller has been initialized before the capture button is used.
The CameraController.takePicture() method captures the current camera frame and returns an XFile. The file is usually stored in a temporary location. You can display it, copy it to permanent storage, or upload it to a server.
Capture flow
A capture operation should:
- Check that the controller exists and is initialized.
- Prevent another capture while one is running.
- Await
takePicture(). - Store or display the returned
XFile. - Handle
CameraExceptionand other failures.
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class CaptureScreen extends StatefulWidget {
const CaptureScreen({
required this.controller,
super.key,
});
final CameraController controller;
@override
State<CaptureScreen> createState() => _CaptureScreenState();
}
class _CaptureScreenState extends State<CaptureScreen> {
XFile? _photo;
bool _isCapturing = false;
String? _errorMessage;
Future<void> _capturePhoto() async {
final controller = widget.controller;
if (!controller.value.isInitialized || _isCapturing) {
return;
}
setState(() {
_isCapturing = true;
_errorMessage = null;
});
try {
final photo = await controller.takePicture();
if (!mounted) return;
setState(() {
_photo = photo;
});
} on CameraException catch (error) {
if (!mounted) return;
setState(() {
_errorMessage = 'Could not take a picture: ${error.code}';
});
} finally {
if (mounted) {
setState(() {
_isCapturing = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: _photo == null
? CameraPreview(widget.controller)
: Image.network(_photo!.path, fit: BoxFit.contain),
),
if (_errorMessage != null) Text(_errorMessage!),
FilledButton.icon(
onPressed: _isCapturing ? null : _capturePhoto,
icon: const Icon(Icons.camera_alt),
label: Text(_isCapturing ? 'Taking picture...' : 'Take picture'),
),
],
);
}
}The _isCapturing flag disables the button during the asynchronous operation. This prevents overlapping calls, which can produce errors on some devices. The mounted check prevents setState from running after the screen has been removed.
On mobile, an XFile contains a local path. To show that path with Image.file, convert it to a File from dart:io:
import 'dart:io';
Image.file(File(photo.path), fit: BoxFit.contain);The Image.network call in the earlier example is suitable for web, where the path can be a browser blob URL. Choose the rendering widget for the platform your app supports.
Exercise
Why should the capture button be disabled while takePicture is running?
Show answer
It prevents overlapping capture requests and avoids camera errors caused by starting another operation before the first one finishes.