Image Picker in Flutter (Android & iOS)
We’ll see how image picker works in flutter for android and iOS.
Question: What is the image picker?
Ans: Image picker is a plugin that is used to get images from a gallery or camera in the app. Eg. to set profile photos we choose images from the gallery or click a photo.
I’m sharing my flutter for people repository of GitHub where all my codes reside.
Find more information in this video.
Let’s dive into implementation….
We will add a plugin to achieve an image picker (link: https://pub.dev/packages/image_picker_modern ) in pubspec.yaml file as a dependency.
image_picker_modern: ^0.4.12+2
We don’t need to do any configuration in android, but for iOS we have to.
Add the following keys to your Info.plist file, located in <project root>/ios/Runner/Info.plist
:
NSPhotoLibraryUsageDescription
- describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor(Xcode or Android Studio).NSCameraUsageDescription
- describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor(Xcode or Android Studio).NSMicrophoneUsageDescription
- describe why your app needs access to the microphone if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor(Xcode or Android Studio).
I will make your work easy. Open Info.plist as source code and add following in bottom just above </dict>
<key>NSPhotoLibraryUsageDescription</key>
<string>Need to upload image</string>
<key>NSCameraUsageDescription</key>
<string>Need to upload image</string>
<key>NSMicrophoneUsageDescription</key>
<string>Need to upload image</string>
Ok… Till now we added and configured our project for image picker. Let’s start coding.
Import this
import 'package:image_picker_modern/image_picker_modern.dart';
Create a variable as File _image; (import import ‘dart:io’;)
Create a Stateful class and add the following
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child: _image == null ? Text('No image selected.') : Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
This code simply allows a user to click on a fab button which opens image picker. In the body, we are displaying a selected picture.
Well following is code for selecting an image. We’ll call this function on click of a fab button
Future<void> getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery); setState(() {
_image = image;
});
}
You can choose ImageSource as a camera or gallery whatever you required.
For a simple use case, I am using the gallery as ImageSource.
That’s all. We have implemented an image picker in our app. YEAH!!
I’m sharing my flutter for people repository of Github where all my codes reside.