Sub topic 4
Picking an Image from the Gallery or Camera
Assume you know Dart async/await, Flutter stateful widgets, and how to add a package to pubspec.yaml. This chapter uses image_picker, which opens a system-owned gallery or camera application. It does not provide an in-app camera preview. Use the camera plugin when your own screen must control the live camera.
Choose a Source
Add image_picker to the project, then create an ImagePicker instance. Call pickImage with either ImageSource.gallery or ImageSource.camera.
The method returns a Future<XFile?>. XFile represents the selected file. The value is null when the user cancels, so cancellation is a normal result rather than an exception.
flowchart TD
A[User taps choose image] --> B{Selected source}
B -->|Gallery| C[System gallery opens]
B -->|Camera| D[System camera app opens]
C --> E{Image selected?}
D --> E
E -->|Yes| F[XFile returned]
E -->|No| G[null returned]import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class ImageChooser extends StatefulWidget {
const ImageChooser({super.key});
@override
State<ImageChooser> createState() => _ImageChooserState();
}
class _ImageChooserState extends State<ImageChooser> {
final ImagePicker _picker = ImagePicker();
XFile? _selectedImage;
String? _errorMessage;
Future<void> _pickImage(ImageSource source) async {
try {
final image = await _picker.pickImage(
source: source,
maxWidth: 1600,
imageQuality: 85,
);
if (!mounted) return;
setState(() {
_selectedImage = image;
_errorMessage = null;
});
} catch (error) {
if (!mounted) return;
setState(() {
_errorMessage = 'Could not select an image.';
});
debugPrint('Image picker error: $error');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Choose an image')),
body: Center(
child: _selectedImage == null
? Text(_errorMessage ?? 'No image selected')
: Image.file(
File(_selectedImage!.path),
width: 300,
height: 300,
fit: BoxFit.cover,
),
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () => _pickImage(ImageSource.gallery),
child: const Text('Gallery'),
),
ElevatedButton(
onPressed: () => _pickImage(ImageSource.camera),
child: const Text('Camera'),
),
],
),
),
);
}
}maxWidth asks the plugin to downscale the image, and imageQuality requests JPEG compression from 0 to 100. These options reduce memory use and upload size, but they can reduce visual quality.
Handle Cancellation and State Safely
Do not force unwrap the result immediately:
final image = await _picker.pickImage(source: ImageSource.gallery);
final path = image!.path; // Wrong if the user cancelsCheck for null before using the file. The mounted check matters because the user can leave the page while the system picker is open. Calling setState after the widget is removed causes an error.
Image.file uses a local filesystem path and is suitable for mobile and desktop. Web builds need a web-compatible display method because browser file paths do not work like mobile paths.
> callout note > The camera source launches the platform camera application and returns after that application finishes. It does not let your Flutter widget display camera controls or a live preview.
Exercise
Exercise
What value should your code expect when the user opens the gallery and presses Cancel?
Show answer
pickImage returns null, so the code should leave the current selection unchanged or show an appropriate empty state.