Sub topic 4
Picking an image from the gallery or camera
This chapter covers the core image_picker workflow: asking the system for a single image, handling the result, and avoiding the errors that most often break it. It assumes you know async/await and Futures, can use StatefulWidget and setState, and can add a package to pubspec.yaml. It also assumes you have already added the Android and iOS configuration from the platform setup chapter. The Info.plist keys matter most here. Without them, iOS can terminate your app when you request the camera or the photo library.
What `pickImage` does
image_picker does not draw its own UI. When you call pickImage, the plugin starts a system screen, either the gallery (photo picker) or the camera app. Your Dart code waits on a Future. The Future completes when the user finishes or backs out.
This design has three consequences:
- Your app does not need to build a gallery or camera interface.
- On most platforms, picking from the gallery needs no runtime permission, because the user chooses the file in a system-owned screen.
- You get no live preview and little control over the camera app. If you need either, use the
cameraplugin instead.
The method signature you use most often is:
Future<XFile?> pickImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
bool requestFullMetadata = true,
})The result is an XFile?. It is null when the user cancels. That is a normal outcome, not an error, so check for it every time.
A first working example
The following complete app shows a button and the picked image. It picks from the gallery and renders the result.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(const MaterialApp(home: PickerDemo()));
class PickerDemo extends StatefulWidget {
const PickerDemo({super.key});
@override
State<PickerDemo> createState() => _PickerDemoState();
}
class _PickerDemoState extends State<PickerDemo> {
final ImagePicker _picker = ImagePicker();
XFile? _picked;
bool _busy = false;
Future<void> _pick(ImageSource source) async {
if (_busy) return;
setState(() => _busy = true);
try {
final XFile? file = await _picker.pickImage(
source: source,
maxWidth: 1024,
imageQuality: 85,
);
if (!mounted) return;
setState(() => _picked = file ?? _picked);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Could not pick an image: $e')),
);
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
final file = _picked;
return Scaffold(
appBar: AppBar(title: const Text('Image picker')),
body: Center(
child: file == null
? const Text('No image selected')
: Image.file(File(file.path), fit: BoxFit.cover),
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton(
heroTag: 'gallery',
onPressed: _busy ? null : () => _pick(ImageSource.gallery),
child: const Icon(Icons.photo_library),
),
const SizedBox(height: 12),
FloatingActionButton(
heroTag: 'camera',
onPressed: _busy ? null : () => _pick(ImageSource.camera),
child: const Icon(Icons.photo_camera),
),
],
),
);
}
}A few details in this code are worth noting:
- One
ImagePickerinstance is stored in the State. It is cheap and holds no resources, so you do not need to dispose of it. file ?? _pickedkeeps the previous image when the user cancels. Without it, a cancel would clear the screen.- The
_busyflag prevents a second tap from starting another picker while one is open. On some platforms a second call while one is active throws aPlatformException. mountedis checked after everyawait. The user might leave the screen while the system UI is open.- Each button has its own
heroTag. TwoFloatingActionButtons in one route with the default tag throw an error during navigation. Image.fileworks on mobile only. On web,file.pathis a blob URL, so useImage.network(file.path)there.
The request flow
The diagram shows what happens between your tap and the rendered image.
Gallery versus camera as a source
ImageSource.gallery opens the system photo picker. ImageSource.camera opens the device's camera app, takes one photo, and returns it. Both give you an XFile, so the rest of your code does not need to care which one produced it.
The differences you should plan for:
| Aspect | `ImageSource.gallery` | `ImageSource.camera` |
|---|---|---|
| UI | System photo picker | System camera app |
| Permission | Usually none at runtime | Camera permission is needed |
| iOS `Info.plist` key | `NSPhotoLibraryUsageDescription` | `NSCameraUsageDescription` |
| Android manifest | Nothing for the picker itself | `CAMERA` only if your app declares it elsewhere |
| Simulator or emulator | Works | iOS Simulator has no camera and fails |
| File location | A copy in the app's cache | A new file in the app's cache |
Because the iOS Simulator has no camera, a camera pick there fails with a PlatformException. Test the camera path on a real device.
You can also hint which camera the system app should open first with preferredCameraDevice: CameraDevice.front. This is a request, not a guarantee. Some Android camera apps ignore it.
Reading the result
An XFile is a thin handle with a few members. These are the ones you use right after picking:
pathis a string. On mobile it points to a file in your app's cache directory. On web it is a blob URL.nameis the file name.readAsBytes()returns the content asFuture<Uint8List>. It works on every platform, including web.length()returns the size in bytes.mimeTypemay benull. Do not rely on it. Check the file extension or inspect the bytes if the type matters.
A common mistake is treating path as permanent. The picked file lives in a cache. The system may clear it, and a reinstall removes it. If the user must keep the image, copy it into a durable location. Later chapters cover copying and uploading.
What the options do
maxWidth, maxHeight, and imageQuality ask the plugin to resize and recompress before returning the file.
- If you pass only
maxWidth, the height scales to keep the aspect ratio. Passing both can still preserve the ratio. The image is scaled to fit inside the box and is never stretched. imageQualityis a number from 0 to 100. It applies mainly to JPEG output. Passing a value outside that range throws anArgumentError.- Passing any of these three options makes the plugin re-encode the image. Re-encoding can drop some metadata, and a PNG may come back with a different format on some platforms. If you want the original bytes, pass none of them.
requestFullMetadatadefaults totrue. On iOS it makes the plugin ask for extra photo-library access to read fields like location. If you do not need that metadata, set it tofalseto avoid the additional permission prompt.
A practical default for profile photos or uploads is maxWidth: 1024 and imageQuality: 85. This cuts a 12-megapixel photo from several megabytes to a few hundred kilobytes with little visible loss.
Common errors and their causes
Most failures fall into a small set of cases.
- The app closes the moment you open the camera on iOS. The
NSCameraUsageDescriptionkey is missing fromInfo.plist. Add it, then do a full rebuild. A hot reload does not pick up plist changes. PlatformException(camera_access_denied)on iOS. The user refused camera permission earlier. The system will not ask again. Your app must tell the user to enable access in Settings.PlatformException(no_available_camera)on a simulator or emulator. There is no camera device. Use a real device or configure the emulator's virtual camera.- The result is
nulland nothing is shown. The user cancelled. Handle it as a normal case, as in the example. - Your widget state is gone after taking a photo on Android. Android may destroy your activity while the camera app is in the foreground. The result then arrives through a recovery call instead of the Future. A later chapter covers
retrieveLostData. setState() called after dispose(). You updated state after anawaitwithout checkingmounted.
Wrap picker calls in try/catch and show a message. Do not let a PlatformException escape to the framework as an unhandled error.
Putting the pieces together
The working pattern for any single pick has five steps:
- Guard against a second call while one is running.
- Call
pickImagewith the source and size options. - Check
mountedafter the await. - Treat
nullas a cancel and keep the previous state. - Catch
PlatformExceptionand show a message the user can act on.
Exercise
A user taps the camera button, grants permission, takes a photo, and returns to your app, but the screen still shows "No image selected". The code has no error. Name two different causes, one that is normal and one that is a bug in your code.
Show answer
The normal cause is that the user cancelled, so pickImage returned null and the code correctly kept the old state. A bug could be that the code never calls setState with the returned file, or that it calls setState only when mounted is true while the widget was already disposed. A third cause on Android is that the activity was destroyed while the camera app was open, so the result must be recovered with retrieveLostData.
Exercise
You pass imageQuality: 85 and maxWidth: 1024 to pickImage. The original photo is 4000 by 3000 pixels. What size do you expect the returned image to be, and why might the returned file's bytes differ from the original even for a photo that was already 800 pixels wide?
Show answer
The result is about 1024 by 768 pixels, because the height scales to keep the aspect ratio. For an 800-pixel-wide photo, the width stays at 800 because maxWidth only shrinks images. The bytes can still differ because passing imageQuality makes the plugin re-encode the image, which changes the compression and may remove metadata.