Image Picker Flutter Example

In this post, We are integrating image picker to capture image from camera and to select image from gallery in flutter application.

We are using custom plugin to integrate flutter image picker in this example. For this first we need to add plugin in our project by adding dependency in our pubspec.yaml file. You can also check out how to integrate image picker in android native platform at HERE.

 

Add required dependency in your pubspec.yaml file

After adding following line in your pubspec.yaml file, Click on pub upgrade button to add latest version of this image picker plugin in your project.

image_picker:
 
 

Support native platforms for Camera and Gallery access

We do not need to do anything for camera and gallery access in Android platform. For iOS platform, we need to add following keys in Info.plist under ios/Runner folder.

<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>

<key>NSCameraUsageDescription</key>
<string>Allow access to camera to capture photos</string>

<key>NSMicrophoneUsageDescription</key>
<string>Allow access to microphone</string>

 
 

Image Picker UI

Center(
    child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
            displayImage(),
            SizedBox(height: 30),
            RaisedButton(
                    onPressed: () {
                        showOptionsDialog(context);
                    },
                child: Text(“Select Image”),
            )
        ],
    ),
),
 
 

Manage UI for image selected or not

We first set UI for both image selected or not. If image is not selected then we display simple alert otherwise selected image is displayed.

Widget displayImage(){
    if(imgFile == null){
        return Text(“No Image Selected!”);
    } else{
        return Image.file(imgFile, width: 350, height: 350);
    }
}
 
 

Show Options Dialog For Camera and Gallery in Image Picker

We display options dialog to choose option from camera and gallery on click of select image button.

Future<void> showOptionsDialog(BuildContext context) {
return showDialog(
    context: context,
    builder: (BuildContext context) {
        return AlertDialog(
            title: Text(“Options”),
            content: SingleChildScrollView(
                child: ListBody(
                    children: [
                        GestureDetector(
                            child: Text(“Capture Image From Camera”),
                            onTap: () {
                                openCamera();
                            },
                        ),
                        Padding(padding: EdgeInsets.all(10)),
                        GestureDetector(
                            child: Text(“Take Image From Gallery”),
                            onTap: () {
                                openGallery();
                            },
                        ),
                    ],
                ),
            ),
        );
    }
);
}
 
 

Capture Image from Camera using Image Picker

Now ImagePicker.pickImage method is deprecated. So first we need to create instance of ImagePicker. Then we can pass source camera in getImage method. We only get image file path from image picker. So we need to convert it into File class.

After obtaining image we store it into imgFile variable in setState method. So page is refreshed and new image is displayed. To hide options dialog after selecting image, we need to use pop method of navigator class.

File imgFile;
final imgPicker = ImagePicker();

void openCamera() async {
    var imgCamera = await imgPicker.getImage(source: ImageSource.camera);
    setState(() {
        imgFile = File(imgCamera.path);
    });
    Navigator.of(context).pop();
}

 
 

Select Image from Gallery using Image Picker

We need to same process as we did for camera. Only change is in image source parameter in getImage mehod.

File imgFile;
final imgPicker = ImagePicker();

void openGallery() async {
    var imgGallery = await imgPicker.getImage(source: ImageSource.gallery);
    setState(() {
        imgFile = File(imgGallery.path);
    });
    Navigator.of(context).pop();
}

 
 

Final Code

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyPickImageScreen(title: 'Flutter Image Picker Sample'),
    );
  }
}

class MyPickImageScreen extends StatefulWidget {
  MyPickImageScreen({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyPickImageScreenState createState() => _MyPickImageScreenState();
}

class _MyPickImageScreenState extends State<MyPickImageScreen> {

  File imgFile;
  final imgPicker = ImagePicker();

  Future<void> showOptionsDialog(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Options"),
            content: SingleChildScrollView(
              child: ListBody(
                children: [
                  GestureDetector(
                    child: Text("Capture Image From Camera"),
                    onTap: () {
                      openCamera();
                    },
                  ),
                  Padding(padding: EdgeInsets.all(10)),
                  GestureDetector(
                    child: Text("Take Image From Gallery"),
                    onTap: () {
                      openGallery();
                    },
                  ),
                ],
              ),
            ),
          );
        });
  }

  void openCamera() async {
    var imgCamera = await imgPicker.getImage(source: ImageSource.camera);
    setState(() {
      imgFile = File(imgCamera.path);
    });
    Navigator.of(context).pop();
  }

  void openGallery() async {
    var imgGallery = await imgPicker.getImage(source: ImageSource.gallery);
    setState(() {
      imgFile = File(imgGallery.path);
    });
    Navigator.of(context).pop();
  }

  Widget displayImage(){
    if(imgFile == null){
      return Text("No Image Selected!");
    } else{
      return Image.file(imgFile, width: 350, height: 350);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
           displayImage(),
            SizedBox(height: 30),
            RaisedButton(
              onPressed: () {
                showOptionsDialog(context);
              },
              child: Text("Select Image"),
            )
          ],
        ),
      ),
    );
  }

}
 
 
 
 
image picker flutter
 
 
image picker flutter
 
 
 
image picker flutter
 
 
 
 

Leave a Reply