Sub topic 13
Handling denied permissions and errors
A camera feature fails in ways that ordinary widgets don't. The user can refuse access, the device can have no camera, or another app can already be using it. This chapter shows how each plugin reports these failures and how to turn them into screens the user can act on.
This chapter assumes you have these from earlier chapters:
- You can declare the Android and iOS permission entries (
NSCameraUsageDescriptionand the others). - You can initialize a
CameraController. - You know that
image_pickerreturns anXFile?.
Two plugins, two failure styles
image_picker and camera report problems differently, so you need separate handling for each.
| Plugin | Failure type | Where it surfaces |
|---|---|---|
| `image_picker` | `PlatformException` with a snake_case `code` | `pickImage`, `pickMultiImage`, `pickVideo` |
| `camera` | `CameraException` with a PascalCase `code` | `availableCameras`, `initialize`, `takePicture`, recording calls |
Cancelling is not a failure. When the user closes the picker without choosing anything, pickImage returns null. Treat null as "nothing happened" and show no error.
The permission flow
The permission prompt appears the first time your code touches the camera, not when the app starts. The plugin asks the operating system, and the answer decides what the next call does.
Error codes from the camera plugin
The code string on a CameraException tells you what to show.
| Code | Meaning |
|---|---|
| `CameraAccessDenied` | The user refused camera access. |
| `CameraAccessDeniedWithoutPrompt` | Camera access was refused earlier and the system will not ask again. iOS only. |
| `CameraAccessRestricted` | Parental controls or device management block the camera. iOS only. |
| `AudioAccessDenied` | The user refused microphone access. It only matters when `enableAudio` is `true`. |
| `AudioAccessDeniedWithoutPrompt` | The same as the camera version, for the microphone. iOS only. |
| `AudioAccessRestricted` | The same as the camera version, for the microphone. iOS only. |
On Android the plugin uses CameraAccessDenied for both a first refusal and a permanent one. The plugin does not let you tell them apart. If you need that distinction, use a permission package such as permission_handler, which exposes isPermanentlyDenied.
Classifying camera errors
Don't scatter catch blocks and string comparisons through your widgets. Put the mapping in one function and let the UI work with an enum.
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
enum CameraFailure { denied, deniedPermanently, restricted, other }
CameraFailure classify(CameraException e) {
switch (e.code) {
case 'CameraAccessDenied':
case 'AudioAccessDenied':
return CameraFailure.denied;
case 'CameraAccessDeniedWithoutPrompt':
case 'AudioAccessDeniedWithoutPrompt':
return CameraFailure.deniedPermanently;
case 'CameraAccessRestricted':
case 'AudioAccessRestricted':
return CameraFailure.restricted;
default:
return CameraFailure.other;
}
}
Future<CameraFailure?> initializeSafely(CameraController controller) async {
try {
await controller.initialize();
return null;
} on CameraException catch (e) {
debugPrint('Camera error ${e.code}: ${e.description}');
return classify(e);
}
}
Future<List<CameraDescription>> listCamerasSafely() async {
try {
return await availableCameras();
} on CameraException catch (e) {
debugPrint('Could not list cameras: ${e.code}');
return const [];
}
}initializeSafely returns null on success and a CameraFailure otherwise. The caller never sees an exception, so it can't forget to catch one.
The empty camera list
Earlier chapters used cameras.first. That call throws a StateError when the list is empty. Emulators without a configured camera and some tablets and desktop targets return an empty list. Check isEmpty first and show a "no camera found" message.
Handling errors from the picker
image_picker throws a PlatformException. The common codes come from the iOS side: camera_access_denied, camera_access_restricted, photo_access_denied, and photo_access_restricted. Both platforms can also throw already_active when a second picker opens while one is running. Android can throw no_available_camera when you ask for ImageSource.camera on a device with no camera app.
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
enum PickerFailure { accessDenied, accessRestricted, busy, noCamera, other }
class PickResult {
const PickResult.picked(this.file) : failure = null;
const PickResult.failed(this.failure) : file = null;
const PickResult.cancelled()
: file = null,
failure = null;
final XFile? file;
final PickerFailure? failure;
}
Future<PickResult> pickSafely(ImagePicker picker, ImageSource source) async {
try {
final XFile? file = await picker.pickImage(source: source);
return file == null
? const PickResult.cancelled()
: PickResult.picked(file);
} on PlatformException catch (e) {
switch (e.code) {
case 'camera_access_denied':
case 'photo_access_denied':
return const PickResult.failed(PickerFailure.accessDenied);
case 'camera_access_restricted':
case 'photo_access_restricted':
return const PickResult.failed(PickerFailure.accessRestricted);
case 'already_active':
return const PickResult.failed(PickerFailure.busy);
case 'no_available_camera':
return const PickResult.failed(PickerFailure.noCamera);
default:
return const PickResult.failed(PickerFailure.other);
}
}
}PickResult has three states: picked, failed, and cancelled. This keeps "the user backed out" separate from "something broke", which a bare null can't do.
Not every gallery pick needs a permission. On current Android versions and on iOS 14 and later, the system photo picker runs in its own process and returns only what the user selects. Your app may never see a permission prompt for gallery access. Code that works on one OS version can therefore behave differently on another, so test on several.
Showing a useful fallback
A failed initialization should lead to a screen with a next step. Match the step to the failure.
| Failure | What to show | Action |
|---|---|---|
| `denied` | Why you need the camera | A button that retries `initialize` |
| `deniedPermanently` | Instructions to enable the camera in Settings | A button that opens app settings |
| `restricted` | A note that the device blocks the camera | No action to offer |
| `other` | A generic "camera unavailable" message | A retry button |
Retrying means building a new controller. A controller whose initialize failed is not reusable, so dispose it first and create another.
Future<void> _retry() async {
await _controller?.dispose();
setState(() {
_initFuture = _setup();
});
}Opening the system settings page needs a package. permission_handler provides openAppSettings(). camera and image_picker have no such call.
Errors after initialization
Permission is only one source of errors. Once the controller is running, failures can still occur.
takePicturethrows aCameraExceptionif the controller is not initialized or if a capture is still pending. Disable the shutter button while a capture runs.- Any call on a disposed controller throws. Check the lifecycle handling from the previous chapter if you see this.
controller.value.hasErrorandcontroller.value.errorDescriptionreport errors raised by the platform after setup, such as the camera being taken by another app. Listen to the controller withaddListeneror aValueListenableBuilderif you want to react.
Wrap capture the same way you wrapped initialization:
Future<XFile?> captureSafely(CameraController controller) async {
if (!controller.value.isInitialized || controller.value.isTakingPicture) {
return null;
}
try {
return await controller.takePicture();
} on CameraException catch (e) {
debugPrint('Capture failed ${e.code}: ${e.description}');
return null;
}
}Common mistakes
- Missing manifest or Info.plist entries. On iOS, a missing usage description crashes the app when the camera opens. Android reports it as a denial. Re-check platform setup before blaming your Dart code.
- Catching
Exceptiontoo broadly. A genericcatch (e)hides programming errors such asStateError. CatchCameraExceptionandPlatformExceptionspecifically. - Treating
nullfrom the picker as an error. It means the user cancelled. - Showing the error only in the debug console. Users don't see
debugPrint. Always map the failure to a visible state. - Forgetting the microphone. With
enableAudio: true, a denied microphone makesinitializefail even though the camera is allowed. SetenableAudio: falsefor photo-only screens.
Exercise
A photo-only screen creates its controller with enableAudio: true. A user allows the camera but denies the microphone, and the preview never appears. Why does this happen, and what is the simplest fix?
Show answer
With enableAudio: true, initialize also needs microphone access. When the microphone is denied, the plugin throws a CameraException with code AudioAccessDenied, so the controller never becomes ready. A photo-only screen doesn't need audio, so set enableAudio: false in the CameraController constructor. That also lets you drop the microphone usage description from the screen's requirements, unless another feature in the app uses it.
Exercise
pickSafely returns PickResult.cancelled() when pickImage returns null. Why is this better than returning PickResult.failed(PickerFailure.other) in that case?
Show answer
A user who closes the picker has not hit an error, so showing an error message would be wrong and confusing. A separate cancelled state lets the UI do nothing, and it keeps real failures such as photo_access_denied distinct in logs and analytics.