Build An Image Picker Wrapper Widget In Flutter

In this post, we will learn to build an image picker wrapper widget in Flutter app that can be used to switch between camera and gallery.

Introduction

For uploading images from Flutter app, Google team has a plugin called “image_picker“. With the help of this library, we can pick images from device gallery as well as take new picture from camera.

In this article we will create a wrapper button that allows us to choose between gallery and camera. Based upon the selection we will pick images to load in the Flutter application.

Setup Image Picker Icon

As usual, let’s start with a simple setup of a Material App.

Material App Container

Setup Image Picker
Setup Image Picker

All we have so far is a camera icon button. Now on the pressed event of this button, we want to allow the user to choose between camera or gallery option.

Setup OnPressed Event For The Camera Icon

For this, we will make use of the showDialog function. It will display a Material dialog above the current contents of the app.

On the onPressed event for the icon, add:

Image Picker Click 1
Image Picker Click 1

Making Use Of The Image Picker

Finally we will make use of the pickImage function of the “image_picker” plugin.

The required parameter “source” is an enum value representing camera and gallery. The other two parameters are optional values for max height and width of the image. It returns the selected image as a File object.

Wrapping Up

Let’s make some final enhancements to our image picker class. We will add some fields that can be passed via the constructor of the class:

The onImageSelected callback allows us to make our image picker wrapper widget reusable.

Next, add a function that handles user selection between camera and gallery.

Finally call the _getImage function.

Our final code: