Sub topic 1
image_picker or camera: which one do you need?
Prerequisites
You should know Dart async/await and Futures, the StatefulWidget lifecycle (initState and dispose), how to add packages in pubspec.yaml, and the basic layout of the android and ios project folders.
image_picker or camera: which one do you need?
The image_picker package opens the system gallery or camera app and returns the chosen file to your app. The camera package shows a live preview inside your own screen and captures from it.
- Use
image_pickerfor a simple photo upload, such as a profile picture. - Use
camerawhen you need custom controls, an overlay, or a continuous preview.
Configuring Android and iOS
Both platforms need declarations before the plugins work.
- iOS: Add usage descriptions to
ios/Runner/Info.plist. WithoutNSCameraUsageDescriptionandNSPhotoLibraryUsageDescription, the app crashes when it touches the camera or photo library. - Android: The
cameraplugin needs<uses-permission android:name="android.permission.CAMERA"/>inandroid/app/src/main/AndroidManifest.xml. Theimage_pickerplugin uses the system picker, so it usually needs no extra permission.
<!-- ios/Runner/Info.plist -->
<key>NSCameraUsageDescription</key>
<string>This app uses the camera to take photos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app lets you choose photos from your library.</string>Understanding XFile
XFile is the cross-platform file type that image_picker returns. It exposes a path, a name, and a readAsBytes() method. On mobile, the path points to a temporary copy in the app's cache. On web, the path is a blob URL, so display it with Image.network instead of Image.file.
Picking an image from the gallery or camera
import 'package:image_picker/image_picker.dart';
final ImagePicker _picker = ImagePicker();
Future<XFile?> pickFromGallery() {
return _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 1024,
imageQuality: 85,
);
}
Future<XFile?> takePhoto() {
return _picker.pickImage(source: ImageSource.camera);
}pickImage returns null when the user cancels, so check the result before you use it. ImageSource.gallery opens the photo library, and ImageSource.camera opens the system camera app.
Exercise
Why is the return type of pickImage nullable (XFile?)?
Show answer
The user can cancel the picker without choosing anything. In that case no file is returned, and the value is null.