Sub topic 11
Taking a picture
Once a CameraPreview is on screen, taking a photo takes one call: CameraController.takePicture(). This chapter covers what that call does, how to guard it against bad states, where the file ends up, and how to keep it. It assumes you have a working initialized controller and preview from the previous chapters. You should also be comfortable with async/await, StatefulWidget, and the mounted check.
What takePicture does
takePicture() returns a Future<XFile>. The plugin captures a still frame from the active camera, writes it to a file, and gives you an XFile that points to that file. The call has three properties to remember:
- It needs an initialized controller. Calling it earlier throws a
CameraException. - It handles one capture at a time. A second call before the first completes throws a
CameraException. - The file is temporary. The plugin writes it to the app's cache area, and the operating system can delete it later.
Capture is separate from preview. The preview is a texture that keeps running while you capture, so the user sees no freeze.
Guarding the call
Users tap buttons repeatedly. The controller exposes its state through controller.value, a CameraValue. Two fields matter here:
isInitializedistrueonceinitialize()has completed.isTakingPictureistruewhile a capture is in flight.
Check both before capturing, and catch CameraException for failures you cannot predict, such as a camera that is disconnected mid-session.
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
Future<XFile?> captureSafely(CameraController controller) async {
final value = controller.value;
if (!value.isInitialized || value.isTakingPicture) {
return null;
}
try {
return await controller.takePicture();
} on CameraException catch (e) {
debugPrint('Capture failed ${e.code}: ${e.description}');
return null;
}
}Returning null for both "ignored" and "failed" keeps the caller simple. If you need different messages for each case, return a small result type or rethrow.
Where the file goes, and how to keep it
The XFile path points into the app's temporary storage. That is fine for showing a preview or uploading right away. If the photo must survive a restart or a cache cleanup, copy it somewhere permanent. XFile.saveTo(path) copies the bytes to a path you choose.
This example uses path_provider for the documents folder and path for joining. Add both to pubspec.yaml with flutter pub add path_provider path.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<File> keepPermanently(XFile shot) async {
final dir = await getApplicationDocumentsDirectory();
final name = 'photo_${DateTime.now().millisecondsSinceEpoch}.jpg';
final target = p.join(dir.path, name);
await shot.saveTo(target);
return File(target);
}Two details matter here. First, the timestamp makes the name unique, so a second photo does not overwrite the first. Second, saveTo does not delete the original, so the cache copy still exists until the OS removes it. This copy also does not put the photo in the user's gallery. Saving to the gallery needs a separate plugin and extra permissions.
A shutter button that protects itself
The guard in captureSafely blocks overlapping captures at the plugin level. A UI-level flag adds feedback, so the button looks disabled while the work, including the file copy, finishes. The widget below combines both and reports the saved file through a callback.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
class ShutterButton extends StatefulWidget {
const ShutterButton({
super.key,
required this.controller,
required this.onSaved,
});
final CameraController controller;
final ValueChanged<File> onSaved;
@override
State<ShutterButton> createState() => _ShutterButtonState();
}
class _ShutterButtonState extends State<ShutterButton> {
bool _busy = false;
Future<void> _onPressed() async {
setState(() => _busy = true);
try {
final value = widget.controller.value;
if (!value.isInitialized || value.isTakingPicture) return;
final XFile shot = await widget.controller.takePicture();
final dir = await getApplicationDocumentsDirectory();
final name = 'photo_${DateTime.now().millisecondsSinceEpoch}.jpg';
final target = p.join(dir.path, name);
await shot.saveTo(target);
if (!mounted) return;
widget.onSaved(File(target));
} on CameraException catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Could not take photo: ${e.code}')),
);
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: _busy ? null : _onPressed,
child: _busy
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.camera_alt),
);
}
}The mounted checks matter because the user can leave the screen while takePicture or saveTo is running. Without them, calling setState or ScaffoldMessenger.of(context) on a disposed State throws. The finally block resets the busy flag on every exit path, including the early return for an unready controller.
Use the button in a screen's floatingActionButton, and pass the File it reports to whatever shows or stores the result. In the earlier chapter's CameraScreen, you would replace the inline FloatingActionButton with ShutterButton(controller: _controller!, onSaved: ...) once the controller is ready.
Showing the result
A common flow is capture, review, then accept or retake. Pass the file to a review screen and render it with Image.file:
import 'dart:io';
import 'package:flutter/material.dart';
class ReviewScreen extends StatelessWidget {
const ReviewScreen({super.key, required this.photo});
final File photo;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Review')),
body: Center(child: Image.file(photo)),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.of(context).pop(photo),
child: const Icon(Icons.check),
),
);
}
}Returning the file through Navigator.pop lets the original caller decide what to do next. It might upload the file, store its path in a database, or show it in a form.
Common errors and edge cases
| Symptom | Likely cause | Fix |
|---|---|---|
| `CameraException` about an uninitialized controller | `takePicture` ran before `initialize()` finished, or after `dispose()` | Check `isInitialized`. Show the button only after the init future completes. |
| `CameraException` about a previous capture | Double tap, or a second call before the first returned | Check `isTakingPicture` and disable the button while busy. |
| Photo file missing after restart | The path was in the cache folder and the OS cleared it | Copy with `saveTo` to the documents folder. |
| `setState() called after dispose()` | The user left the screen mid-capture | Check `mounted` after every `await`. |
| Photo is rotated or mirrored on one device | Sensor orientation and front camera behavior differ per device | Test portrait and landscape on real hardware. Read the EXIF data if you process the image. |
| Capture is slow or the file is large | The resolution preset is high | Lower the `ResolutionPreset` when you create the controller. |
Resolution is set when you create the controller, not when you capture, so you cannot request a smaller image per shot. If you need a thumbnail or a smaller upload, resize after capture or pick a lower preset.
Summary
- Call
takePicture()only whenisInitializedis true andisTakingPictureis false. - Catch
CameraExceptionand decide what the user sees. - Treat the returned
XFileas temporary and copy it withsaveToif you need to keep it. - Check
mountedafter eachawaitin widget code.
Exercise
A user takes a photo, closes the app, and opens it the next day. The path you stored from XFile.path now points to a missing file. What happened, and how do you prevent it?
Show answer
takePicture writes to the app's temporary cache folder, and the OS can clear that folder at any time. Prevent it by copying the file with XFile.saveTo(path) to a permanent location, such as one inside getApplicationDocumentsDirectory(), immediately after capture. Store the new path, not the original.
Exercise
In the ShutterButton code, why does _onPressed check mounted after await calls instead of only once at the start?
Show answer
The widget can be removed from the tree while an await is pending, for example if the user navigates back during capture or file copying. mounted is only meaningful at the moment you check it, so the check must follow each await that precedes a use of setState, context, or the callback.