DEV Community

Cover image for INTEGRATE IMAGE PICKER SERVICE IN YOUR FLUTTER PROJECT
Samuel Twumasi
Samuel Twumasi

Posted on

INTEGRATE IMAGE PICKER SERVICE IN YOUR FLUTTER PROJECT

Add the image picker plugin in your pubspec.yaml file

There are mainly two ways for adding a package to your project.

First Approach (Long approach)

  1. Head over to pub.dev and search for image_picker 0.8.5+3 Link here.

  2. Click on installing and copy the image picker version image_picker: ^(current version number)

  3. Go to your pubspec.yaml file and paste what you have copied under dependencies and make sure it is properly aligned.

  4. Hit save or run flutter pub get to install all dependencies.

Alternate method (Shorter approach)

  1. Head over to your terminal and run flutter pub add image_picker to add the image picker plugin to your project. As simple as it can be 😀

Implementation of the image picker plugin

  1. In the state of your class (StatefulWIdget), declare a nullable variable File? imageUrl; that will hold the file image. I will explain the reason for making your variable null very shortly.

  2. Now we have to write a function for the image picker.

void selectImage() async {
    final picker = ImagePicker(); //Initialize the image picker service
    final pickedImage = await picker.pickImage();
    if (pickedImage == null) { //Check if the user did not pick any image, then we return.
      return;
    }
   setState((){
     imageUrl = File(pickedImage!.path); //Set imageUrl to the to File of the picked image.
   });
  }
Enter fullscreen mode Exit fullscreen mode

Note that the .pickImage() method has some number of properties you can set, including imageQuality, source and many more.

  1. Now head over to where you want to display your image.
Container(
  height: 200,
  width: 200,
  child: FileImage(imageUrl ?? 'any dummy image url here');//This line checks if imageUrl is null, then it displays the dummy image url else it will display your image. This is where the power or dart nullable comes in 😀.
);
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)