CodeBlanks Logo Icon CodeBlanks

What is image_picker?

Pick an image from gallery or camera with image_picker.

What is image_picker?

The image_picker package lets the user pick an image from the gallery or the camera. You create an instance of ImagePicker and call its pickImage method. The selected image is returned as an XFile.

final picker = ImagePicker();
final file = await picker.pickImage(source: ImageSource.gallery);

The XFile class

XFile is the class that holds the path and metadata of the selected file. You access the file path with file.path; you use this path with Image.file or File to display the image. If the user cancels, null is returned.

if (file != null) {
  print(file.path);
}

Practice Create an ImagePicker instance

Create an ImagePicker instance and print 'ok'.

Starter code

main.dart
class ImagePicker {
  ImagePicker();
}

void main() {
  // ImagePicker örneği oluştur
  // 'ok' yazdır
}

Sample solution

main.dart
class ImagePicker {
  ImagePicker();
}

void main() {
  final picker = ImagePicker();
  print('ok');
}

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the pickImage method of image_picker return?

  • Future<Widget>
  • Future<int>
  • Future<String>
  • Future<XFile?> Correct answer

Explanation: pickImage returns Future<XFile?>; it returns null if the user cancels the selection.

2 Create an ImagePicker

Question
final picker = ____;
Answer
final picker = ImagePicker();

Explanation: To create an instance of ImagePicker you call the ImagePicker() constructor; the parentheses are required.

3 image_picker parts

Term Meaning
ImagePicker Picker class
pickImage Picks an image
XFile Selected file
path File path

All lessons in Advanced