pickImage
- Flutter course
- Advanced
- Lesson 32/69
- 4 min
Pick an image with pickImage.
The pickImage method
The pickImage method takes a source parameter that specifies the image source. ImageSource.gallery picks from the gallery, ImageSource.camera picks from the camera. The method is asynchronous, so you await it with await.
final file = await picker.pickImage(
source: ImageSource.gallery,
);User cancellation
If the user goes back without picking an image, pickImage returns null. Therefore you must check for null before using the returned value. Otherwise a null error is thrown.
final file = await picker.pickImage(
source: ImageSource.gallery,
);
if (file == null) return;Practice Pick an image from the gallery
Create an ImagePicker, pick an image with pickImage from ImageSource.gallery and print the file path.
Starter code
enum ImageSource { gallery, camera }
class XFile {
final String path;
XFile(this.path);
}
class ImagePicker {
Future<XFile?> pickImage({required ImageSource source}) async {
return XFile('/tmp/picked.png');
}
}
void main() async {
// galeriden görsel seç
// dosya yolunu yazdır
}Sample solution
enum ImageSource { gallery, camera }
class XFile {
final String path;
XFile(this.path);
}
class ImagePicker {
Future<XFile?> pickImage({required ImageSource source}) async {
return XFile('/tmp/picked.png');
}
}
void main() async {
final picker = ImagePicker();
final file = await picker.pickImage(source: ImageSource.gallery);
print(file!.path);
}Expected output
/tmp/picked.png
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does ImageSource.camera specify?
- Downloading an image from a URL
- Capturing an image from the camera Correct answer
- Picking an image from the gallery
- Deleting a file path
Explanation: ImageSource.camera specifies capturing an image from the camera; ImageSource.gallery is used to pick from the gallery.
2 Specify the source
final file = await picker.pickImage(
source: ____,
);
final file = await picker.pickImage(
source: ImageSource.gallery,
);
Explanation: To pick from the gallery you use ImageSource.gallery; it is an enum value.
3 pickImage parts
| Term | Meaning |
|---|---|
pickImage |
Picks an image |
source |
Source parameter |
ImageSource.gallery |
Gallery source |
ImageSource.camera |
Camera source |