Flutter tutorial— Image Picker — Picking photos from camera or photo gallery

Itchybumr
2 min readFeb 17, 2021

--

It is very common for mobile apps to provide image uploading functionality. I have tried and tested this Image Picker plugin. It is easy to use and does what it says. This tutorial is based on Image Picker 0.6.7, the latest version.

Final product

Step 1 — add image_picker as a dependency in pubspec.yaml

image_picker: ^0.6.7+22

Step 2— setup IOS/Android

For IOS, open Info.plist file, located in <project root>/ios/Runner/Info.plist. Add the following code.

<key>NSCameraUsageDescription</key>
<string>Allow access to camera</string>
<key>NSMicrophoneUsageDescription</key>
<string>Allow access to microphone for video recording</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>

For Android, check Android API you are using at <project root>/android/app/src/build.gradle. Search for compileSdkVersion. If you are using Android API < 29, no configuration is required. If you are using Android API 29+, open AndroidManifest.xml file, located at <project root>/android/app/src/main/AndroidManifest.xml. Add android:requestLegacyExternalStorage="true" as an attribute to the <application> tag like the following code.

<activity
android:name=".MainActivity"
...
android:requestLegacyExternalStorage="true">

Step 3 — Add Image Picker functions

This code has to be added in stateful widget.

File _image;
final picker = ImagePicker();

//Image Picker function to get image from gallery
Future getImageFromGallery() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);

setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
}
});
}

//Image Picker function to get image from camera
Future getImageFromCamera() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);

setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
}
});
}

Step 4 — Add options to select between camera and gallery

You can use anything really. For me, I choose CupertinoActionSheet.

Future showOptions() async {
showCupertinoModalPopup(
context: context,
builder: (context) => CupertinoActionSheet(
actions: [
CupertinoActionSheetAction(
child: Text('Photo Gallery'),
onPressed: () {
// close the options modal
Navigator.of(context).pop();
// get image from gallery
getImageFromGallery();
},
),
CupertinoActionSheetAction(
child: Text('Camera'),
onPressed: () {
// close the options modal
Navigator.of(context).pop();
// get image from camera
getImageFromCamera();
},
),
],
),
);
}

Step 5— Put everything together

If you found this article helpful and we would like support my writing. You can buy me a coffee at https://www.buymeacoffee.com/itchybum

--

--

Itchybumr

Scratch it when it itch! Making the world less sad, one article at a time