Sub topic 13
Handling denied permissions and errors
Assume you know Dart async and await, Flutter StatefulWidget lifecycles, and how to add packages with pubspec.yaml. Camera and picker plugins cross a platform boundary, so errors can come from Flutter, Android, iOS, or the user.
A permission request is not guaranteed to succeed. The user might deny access, deny it permanently, or cancel a picker without an error. Your app should treat each case differently.
Distinguish cancellation from failure
image_picker returns an XFile? for one image. A null result usually means that the user closed the picker or canceled the operation. It is not an exception.
Platform failures commonly appear as PlatformException. Check its code, log the technical details, and show a short message that explains what the user can do.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
Future<void> chooseImage(BuildContext context) async {
final picker = ImagePicker();
try {
final XFile? image = await picker.pickImage(
source: ImageSource.gallery,
);
if (!context.mounted) return;
if (image == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No image was selected.')),
);
return;
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Selected ${image.name}')),
);
} on PlatformException catch (error) {
if (!context.mounted) return;
debugPrint('Image picker failed: ${error.code}: ${error.message}');
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Photos are unavailable. Check app permissions.'),
),
);
} catch (error, stackTrace) {
debugPrint('Unexpected picker error: $error\n$stackTrace');
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not choose an image.')),
);
}
}The context.mounted check matters because the user can leave the screen while the asynchronous operation is running. Do not use a BuildContext after its widget has been removed.
Handle camera initialization errors
CameraController.initialize() throws CameraException when a camera is unavailable or permission is denied. Keep initialization inside a try block and provide a fallback screen.
Future<void> initializeCamera(CameraController controller) async {
try {
await controller.initialize();
} on CameraException catch (error) {
debugPrint('Camera error: ${error.code}: ${error.description}');
switch (error.code) {
case 'CameraAccessDenied':
case 'CameraAccessDeniedWithoutPrompt':
case 'CameraAccessRestricted':
// Set state so the UI explains how to enable camera access.
break;
default:
// Set state so the UI reports that the camera is unavailable.
break;
}
}
}The exact error codes can differ by platform and plugin version. Use the code for logging and broad handling, but avoid exposing raw platform messages to users.
Design the fallback UI
A permission error should not leave a blank preview or an enabled capture button. Track an explicit state such as cameraUnavailable or permissionDenied. Render a message, a retry action, and, where appropriate, instructions to open the operating system settings.
Do not repeatedly request permission in a build method. Ask from a user action or controlled initialization step. After the user changes permissions in Settings, recreate and initialize the CameraController; an old failed controller will not become valid by itself.
Exercise
What should your app do when pickImage returns null, and what should it do when CameraController.initialize() throws CameraException?
Show answer
Treat null as picker cancellation and leave the screen usable. Catch CameraException, log its code, update the UI with a clear fallback, and offer a retry or settings action.