image picker flutter

    It helps you to

  • Take pictures from Gallery and capture using camera
  • Take Videos from Gallery and record using camera

It’s better to use this plugin than start from scratch.

How to pick image from gallery or take a picture using Camera – Flutter Image_Picker?

flutter-imagepicker-example

Before trying to do amazing things with Image_Picker plugin, Do not forget to add dependency in pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  
  image_picker: ^0.6.7+14


This is the latest version. Starting from 0.6.7, API has changed a lot, If you are using the old versions of this plugin, You should migrate to the new version.

Most important, pickImage is deprecated, you should use ImagePicker.getImage() method instead.

image picker flutter info.plist

iOS developers – You need to add some key value pairs in this file /ios/Runner/Info.plist
ios permission for image picker in flutter


NSPhotoLibraryUsageDescription
Need to take picture from photo library

This will show iOS users when they tried to open the photo library.


NSCameraUsageDescription
Need to take picture using Camera

You don’t need to do anything with Android if you are trying to develop Apps for API 29+

If you are targeting API level below 29, then you need to add


android:requestLegacyExternalStorage="true"

Clean main.dart file and put the below code. You can easily create StatefulWidget by typing stful.

import 'package:flutter/material.dart';

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

class ImagePickerExample extends StatefulWidget {
  @override
  _ImagePickerExampleState createState() => _ImagePickerExampleState();
}

class _ImagePickerExampleState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

Put below code in state class.

//Holds image File
File _image;
//ImagePicker instance.
final picker = ImagePicker();

  • First, you need to create instance of ImagePicker and File.
  • then you need to import below statements.
    • import ‘dart:io’;
    • import ‘package:image_picker/image_picker.dart’;

Let’s create image taking method called _getImage().

//ImageSource: Camera and Gallery.
 _getImage(ImageSource imageSource) async 
{
    PickedFile imageFile = await picker.getImage(source: imageSource);
//if user doesn't take any image, just return.
    if (imageFile == null) return;

    setState(
      () {
//Rebuild UI with the selected image.
        _image = File(imageFile.path);
      },
    );
  }

  • You can directly use ImageSource.camera or ImageSource.gallery in getImage() method. In this way you can implement both features and reduce code.

Let’s complete the build method and make UI.


@override
  Widget build(BuildContext context) 
  {
    return MaterialApp(
      title: 'Flutter ImagePicker Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Image_Picker Example'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: _image != null
                  ? Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Container(
                        width: 300,
                        height: 300,
                        child: Image.file(
                          _image,
                        ),
                      ),
                    )
                  : Padding(
                      padding: const EdgeInsets.all(18.0),
                      child: Text('No image selected'),
                    ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(
                  onPressed: () => _getImage(ImageSource.gallery),
                  icon: Icon(Icons.image),
                  label: Text('gallery'),
                ),
                ElevatedButton.icon(
                  onPressed: () => _getImage(ImageSource.camera),
                  icon: Icon(Icons.camera),
                  label: Text('camera'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

Let’s talk about ImagePicker pickImage() arguments:

  • source: Gallery or Camera.
  • imageQuality: value ranges from 0-100, where 100 is max/original quality. If it’s null, the original quality returned.
  • maxHeight: specify the maximum height of the Image, if it’s not specified original height returned.
  • maxWidth: specify the maximum width of the Image, if it’s null original width returned.
  • preferredCameraDevice: By default, it uses CameraDevice.rear. You can change it to CameraDevice.front.

Flutter Image_Picker – Capture Image & Store Example

image_picker flutter camera take picture

  image_picker: 0.6.7+14
  path_provider: ^1.6.24
  path: ^1.7.0

  • path: Helps us to join path(usage – in this example).
  • path_provider: It gives directory location to store images(usage- in this example).
  • Don’t forget to add iOS permissions and Android, just like first Example. Check out First example, if you don’t know how to do it.

clean main.dart file, and type stful and make StatefulWidget, don’t forget to add main method and import statement or copy the below code.


import 'package:flutter/material.dart';

void main() => runApp(ImageSave());

class ImageSave extends StatefulWidget {
  @override
  _ImageSaveState createState() => _ImageSaveState();
}

class _ImageSaveState extends State {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

just like the first example, create File and ImagePicker instance in state class.


File _image;

final picker = ImagePicker();


Now it’s time to make _getImage() and store it in the device storage.


  _getImage() async 
{
//ImageSource: camera
    PickedFile imageFile = await picker.getImage(source: ImageSource.camera);
//If there is no image selected, return.
    if (imageFile == null) return;
//File created.
    File tmpFile = File(imageFile.path);
//it gives path to a directory - path_provider package.
    final appDir = await getApplicationDocumentsDirectory();
//filename - returns last part after the separator - path package.
    final fileName = basename(imageFile.path);
//copy the file to the specified directory and return File instance.
    tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
//prints file location
    print('File path is :${tmpFile.path}');

    setState(() {
      _image = tmpFile;
    });
  }

  • Copy and paste the below statements.

    • import ‘package:path/path.dart’;
    • import ‘package:path_provider/path_provider.dart’;

Let’s build the User Interface of this app.

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter ImagePicker - Save Image Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ImagePicker - Save Image Example'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Center(
              child:  _image != null
        ?Container(
                height: 300,
                child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Image.file(
                          _image,
                        ),
                      ),)
                    : Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text('No Image found'),
                    ),

            ),
            ElevatedButton(
              child: Text('Capture and Store Image'),
              onPressed: _getImage,
            )
          ],
        ),
      ),
    );
  }

How to view those Image Files stored in Emulator/Device?

view saved images in flutter

How to take Video from Gallery or capture using Camera – Flutter ImagePicker

flutter image_picker record video example

So create a project named flutter_imagepicker_video_example, that’s a long name.

After the project created, open pubspec.yaml and paste the below dependencies,


video_player: ^1.0.1
image_picker: ^0.6.7+14

iOS – ImagePicker

put below keys to info.plist file, located in /ios/Runner/Info.plist.

        NSPhotoLibraryUsageDescription
	permission needed - photo library
	NSCameraUsageDescription
	permission needed - camera
	NSMicrophoneUsageDescription
	permission needed - microphone

Android

if you are making an app for the above API 29, there is no configuration required. For below API 29, add the below attribute to the tag in AndroidManifest.xml.


android:requestLegacyExternalStorage="true"

Let’s configure video_player…

iOS – video_player

Paste below entries to info.plist file


NSAppTransportSecurity

  NSAllowsArbitraryLoads
  



Actually, these keys allow using Video files by URLs.

Android

paste the permission in AndroidManifest.xml




clear your main.dart file and make statefulWidget by typing stful and paste below code.


import 'package:flutter/material.dart';

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

class VideoImagePicker extends StatefulWidget {
  @override
  _VideoImagePickerState createState() => _VideoImagePickerState();
}

class _VideoImagePickerState extends State {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


Let’s make a _pickVideo() method to take video.

//VideoPlayerController instance
VideoPlayerController _videoPlayerController;
//_video holds the selected video file.
  File _video;
//ImagePicker initialized.
  final picker = ImagePicker();

  _pickVideo(ImageSource imagesource) async 
{
    PickedFile pickedFile = await picker.getVideo(source: imagesource);
//User doesn't take the video, return
    if (pickedFile == null) return null;
//_video holds video file.
    _video = File(pickedFile.path);
//Initialize VideoPlayerController with the selected file and rebuild.
    _videoPlayerController = VideoPlayerController.file(_video)
      ..initialize().then((value) {
        setState(() {});
        _videoPlayerController.play();
      });
  }


Let’s build the UI

  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text('Flutter ImagePicker - Pick Video Example'),
          ),
          body: Container(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  (_video != null && _videoPlayerController.value.initialized)
                      ? Expanded(
                    child: AspectRatio(
                      aspectRatio: _videoPlayerController.value.aspectRatio,
                      child: VideoPlayer(_videoPlayerController),
                    ),
                  )
                      : Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('No Videos selected'),
                  ),
                  ElevatedButton.icon(
                    icon: Icon(Icons.camera),
                    onPressed: () {
                      _pickVideo(ImageSource.camera);
                    },
                    label: Text('Record Video Using Camera'),
                  ),
                  ElevatedButton.icon(
                    icon: Icon(Icons.photo),
                    onPressed: () {
                      _pickVideo(ImageSource.gallery);
                    },
                    label: Text('Pick Video From Gallery'),
                  ),
                ],
              ),
            ),
          ),
        ));
  }


That’s all for now. if you like this post, please share it with your family and friends.
ImagePicker Flutter

Please disable your adblocker or whitelist this site!