The image collector is one of the most widely used components in any application. Many popular apps, such as Facebook, Twitter, Instagram, WhatsApp, etc., have an image collector that enables users to select files from their device to use as profile pictures or to share with their friends.

In mobile applications, the most common use case for image pickers is to set up an avatar for a user’s profile. In this tutorial, we will show you how to create an image collector in Flutter. We will build an example of a Flutter application that allows users to select photos from a gallery or take photos from their device’s camera.

Here’s what we have to say.

  • What is a Flutterimage_picker?
  • Build a Flutter image picker application
  • addimage_pickerThe plug-in
  • Creating the widget
  • Test our Flutter image collector application

What is a Flutterimage_picker

Coding an image picker part from scratch in Flutter would be tedious. Flutter comes with an image collector plugin for capturing images from a library of devices or taking new photos from a camera.

The Image_Picker plug-in exposes some useful methods from the ImagePicker class it outputs.

import 'package:image_picker/image_picker.dart';

ImagePicker picker = ImagePicker();

Copy the code

The picker instance has public methods that we will call to open the image selection dialog. Let’s take a look at these methods.

pickImage

XFile? image = await picker.pickImage(source: ImageSource.gallery);

Copy the code

The pickImage method opens the selection dialog and displays the phone’s photo library, from which you select an image. The source parameter indicates where to select the image.

In this case, the source is set to ImageSource. Gallery, so the image is selected from the user’s gallery.

XFile? image = await picker.pickImage(source: ImageSource.camera);

Copy the code

In the example above, the image is extracted from the device’s camera. This method opens the camera and selects the image the user has taken. The camera parameter is the reason to turn on the device camera.

pickVideo

XFile? image = await picker.pickVideo(source: ImageSource.gallery);

Copy the code

This method opens a selection dialog box and selects a video from the phone’s photo library. You use the pickVideo method when you want to pick videos from a photo library or from your phone’s camera. Argsource: ImageSource. Gallery causes the video to be selected from the phone’s gallery.

XFile? photo = await picker.pickVideo(source: ImageSource.camera);

Copy the code

This method allows the user to select videos from the camera. Parameter Source: ImageSource. Camera Turns on the phone’s camera so the user can record video. The recorded video is then used as the selected video.

pickMultiImage

List<XFile>? images = await picker.pickMultiImage(source: ImageSource.gallery);

Copy the code

PickMultiImage allows the user to select multiple images. This parameter allows us to select images from the phone’s photo library.

List<XFile>? photos = await picker.pickMultiImage(source: ImageSource.camera);

Copy the code

Build a Flutter image collector application

Now that we have reviewed the methods in the Image_Picker plug-in, let’s build an example of a Flutter image collector application to see how they work in practice.

Before we begin, make sure you have the following tools and binaries installed on your machine.

  • Flutter SDK. We will use it to compile, create, and run our Flutter project. It has a CLI tool,flutterIt allows us to do these things from the terminal
  • VS code. This is optional, but useful for the code of the Flutter project. VS Code has a great plugin to improve your coding experience with Flutter.
  • Android Studio. This binary is an IDE for building and compiling native Android projects. We can also create, compile and run Flutter projects using Android Studio. But most of the time, we need Android Studio to run the emulator and compile our Flutter project from VS Code.

Build the scaffolding for the Flutter project

Now that we have the necessary tools and binaries installed, it is time to build our Flutter image picker sample application.

First, let’s build a scaffold for the Flutter project.

flutter create imagepickerprj

Copy the code

This will create a Flutter project in a folder called ImagepickerPRj. A series of commands will cascade down on our terminal. At the end of the terminal, you will see instructions for running the newly generated project.

In order to run your application, type:

  $ cd imagepickerprj
  $ flutter run

To enable null safety, type:

  $ cd imagepickerprj
  $ dart migrate --apply-changes

Your application code is in imagepickerprj/lib/main.dart.

Copy the code

We won’t run it now, but let’s move it inside the folder.

cd imagepickerprj

Copy the code

addimage_pickerThe plug-in

The next step is to add the Image_Picker plug-in to our Flutter project.

Open the pubspec.yaml file and add image_picker to the Dependencies section.

Dependencies: flutter: SDK: flutter image_picker: ^0.8.2Copy the code

If you are using VS Code, once you save the pubspec.yaml file, it will automatically pull in image_picker. If you are not using VS Code, run the following command to pull in the newly added dependencies.

flutter pub get

Copy the code

Create components

In our ImagepickerPRj project, our main file is in the lib/ folder. Dart this is the main.dart file, which is the entry point to any Flutter project/application. So this is where we’re going to start adding most of the code.

Flutter already has some code for us, but we won’t need it except in the MyApp Widget. Let’s start there.

void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(), ); }}Copy the code

Our Flutter picture picker application will have two screens.

  • HomePageTwo buttons will be listed:Pick Image from Gallery, andPick Image from CameraPick Image from GalleryWill open aImageFromGalleryExScreen, where we can pick images from our gallery, whilePick Image from CameraWill open aImageFromGalleryExScreen, where we can take a picture from our camera and use that picture as a selection of pictures
  • ImageFromGalleryExWill handle the problem of selecting images from libraries and cameras. It will know what to process based on the type of source sent to it. It will also display the selected image

Now let’s code them.

HomePage

enum ImageSourceType { gallery, camera } class HomePage extends StatelessWidget { void _handleURLButtonPress(BuildContext context, var type) { Navigator.push(context, MaterialPageRoute(builder: (context) => ImageFromGalleryEx(type))); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Image Picker Example"), ), body: Center( child: Column( children: [ MaterialButton( color: Colors.blue, child: Text( "Pick Image from Gallery", style: TextStyle( color: Colors.white70, fontWeight: FontWeight.bold), ), onPressed: () { _handleURLButtonPress(context, ImageSourceType.gallery); }, ), MaterialButton( color: Colors.blue, child: Text( "Pick Image from Camera", style: TextStyle( color: Colors.white70, fontWeight: FontWeight.bold), ), onPressed: () { _handleURLButtonPress(context, ImageSourceType.camera); }, ), ], ), )); }}Copy the code

We have an enumeration, ImageSourceType, that holds the ImageSourceType, gallery and camera. In the HomePage Widget, we have a method, _handleURLButtonPress. This method takes the parameter type, which contains any value of ImageSourceType. It opens the ImageFromGalleryEx Widget and passes the image source type to the Widget class.

In the build method, we see that it renders two buttons, as we said earlier: Pick Image from Gallery, and Pick Image from Camera. An onPressed event is set on each button. These events call the _handleURLButtonPress method when the button is pressed.

The Pick Image from Gallery button passes the ImagesourceType. Gallery to the ImageFromGalleryEx widget, telling it that we are going to Pick an Image from the Gallery. The Pick Image from Camera button passes the ImagesourceType. Camera to the ImageFromGalleryEx widget, telling it to open the phone’s Camera and take the Image taken as the selected Image.

Now, let’s code the ImageFromGalleryEx Widget.

ImageFromGalleryEx

class ImageFromGalleryEx extends StatefulWidget { final type; ImageFromGalleryEx(this.type); @override ImageFromGalleryExState createState() => ImageFromGalleryExState(this.type); } class ImageFromGalleryExState extends State<ImageFromGalleryEx> { var _image; var imagePicker; var type; ImageFromGalleryExState(this.type); @override void initState() { super.initState(); imagePicker = new ImagePicker(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(type == ImageSourceType.camera ? "Image from Camera" : "Image from Gallery")), body: Column( children: <Widget>[ SizedBox( height: 52, ), Center( child: GestureDetector( onTap: () async { var source = type == ImageSourceType.camera ? ImageSource.camera : ImageSource.gallery; XFile image = await imagePicker.pickImage( source: source, imageQuality: 50, preferredCameraDevice: CameraDevice.front); setState(() { _image = File(image.path); }); }, child: Container( width: 200, height: 200, decoration: BoxDecoration( color: Colors.red[200]), child: _image!= null? Image.file(_image, width: 200.0, height: 200.0, fit: boxfit.fitheight,) : Container(decoration: BoxDecoration( color: Colors.red[200]), width: 200, height: 200, child: Icon( Icons.camera_alt, color: Colors.grey[800], ), ), ), ), ) ], ), ); }}Copy the code

Here, we have imagefromgallery x, a stateful widget, and ImageFromGalleryExState, which holds the state of the imagefromgallery x widget.

In the ImageFromGalleryExState widget, we have the following variables.

  • _imageSave the selected image, either from the gallery or from the camera.
  • imagePickerkeepImagePickerInstances of the class
  • typeSaves the type of image source the widget will use. It is fromHomePageWidget to widget.

We also have an initState method, which is first inserted into the widget tree. We use this method to initialize and create an instance of the ImagePicker class, and then assign it to the ImagePicker variable.

Inside the Build method is the Container Widget, which is a subroutine of the Center Widget. We render image.file based on the conditions of the _image variable. If _image is not empty or undefined, then we know that it has an Image, and we render the image.file widget by passing the _image variable to it.

The image.file is a widget that renders images stored locally on the device. If there is nothing in the _image variable, we render the Container widget. The Container displays a camera icon.

GestureDetector is the parent of all of these widgets. It has an onTap event registered with it. This event is triggered when the widget inside the GestureDetector is clicked. The onTap handler calls the pickImage method from the imagePicker instance. It infers the source of the image from the type variable and passes it to the pickImage method. It then passes the imageQuality (imageQuality: 50) and finally the preferredCameraDevice, preferredCameraDevice: cameradevice.front. This makes it choose our phone’s front-facing camera.

Now, the pickImage returns an XFile instance. We reference the image.path returned by image from the XFile instance and pass it to File to create a File instance from it. This XFile instance is what we set to the _image state.

setState(() {
    _image = File(image.path);
});

Copy the code

This will cause the ImageFromGalleryExState to be re-rendered, and image.file will display the Image in the _image variable.

Now that we’re done with the code, let’s test and run our application.

Test our Flutter image collector application

Open your Android emulator, from your terminal, and run the following command.

flutter run

Copy the code

This will compile and build the project, and then run the application in your Android emulator.

If you are using VS code, you can run the above command, or simply right click lib/main.dart in the editor and then run Without Debugging or Start Debugging.

The app will open in your Android emulator.

HomePage

Select images from the gallery

Selects an image from the camera

conclusion

We’ve learned a lot in this tutorial. We first introduced common use cases for the Flutter image collector component. Then, we introduced the image_Picker plugin for Flutter. We learned how to initialize the ImagePicker class of the Image_Picker plug-in and reviewed the methods in the ImagePicker class.

Finally, we built a Flutter project to demonstrate how to use the Image_Picker plug-in in real-world scenarios.

Find the source code for the project on GitHub.

The postBuilding an image picker in Flutterappeared first onLogRocket Blog.