Flutter

How to pick image from gallery and camera in flutter.

Image picking is an essential component almost in every app where user has his profile. A very common example of this is to pick user profile image from gallery. In this tutorial we will learn how to pick image form gallery and camera. We will make a sample app to demonstrate it. Let’s start.

Create Flutter Project

We will create a new flutter app and add image_picker library in pubspec.yaml file like this.

dependencies:
  flutter:
    sdk: flutter
  image_picker: ^0.8.4+4

Now run the “flutter pub get” command in terminal to install the package in your project.

Platform Specific Configuration

We have to do some configuration for Android and IOS to pick image from gallery or camera. This configuration is compulsory for pick image.

IOS Configuration

Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, NSMicrophoneUsageDescription to your Info.plist file.

        <dict>

	  <key>NSPhotoLibraryUsageDescription</key>
	  <string>Upload images for screen background</string>
	  <key>NSCameraUsageDescription</key>
	  <string>Upload image from camera for screen background</string>
	  <key>NSMicrophoneUsageDescription</key>
	  <string>Post videos to profile</string>

	</dict>

Android Configuration

In android  API 29+ , no configuration is required. And for API < 29 we have to add this android:requestLegacyExternalStorage=”true”  in manifest file in application tag.

	<application
	        android:requestLegacyExternalStorage="true"
	        android:name="io.flutter.app.FlutterApplication"
	        android:label="xxxxxx"
	        android:icon="@mipmap/launcher_icon">
	        <activity>
	                ...
	                ...
	        </activity>
	</application>

Pick image from gallery and camera

After doing platform specific configuration now we will do flutter code to pick image. Flutter makes it very easy to pick image from gallery. In this simple example we will pick image from gallery and will show this image on Image.file() widget. Let’s do it.

First create a file object in MyHomePageState

File? _imagefile;

Now create a function _pickImageFromGallery()

_pickFromGallery() async {
  PickedFile? image = await ImagePicker.platform
      .pickImage(source: ImageSource.gallery, imageQuality: 100);
   setState(() {
    _imagefile = File(image!.path);
  });
}

This function will open the gallery to pick image from there. To take image form camera you just need to change the Image source.

_takeImageFromCamera() async {
  PickedFile? image = await ImagePicker.platform
      .pickImage(source: ImageSource.camera, imageQuality: 100);
   setState(() {
    _imagefile = File(image!.path);
  });
}

Here is the complete code of this.

main.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:my_demo/user.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
         
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File? _imagefile;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Picker Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(

           children: [
            if (_imagefile != null)
              Image.file(
                _imagefile!,
                width: 300,
                height: 300,
              ),
            Align(
              alignment: Alignment.center,
              child: ElevatedButton(
                  onPressed: () {
                    _pickFromGallery();
                  },
                  child: const Text('Pick Image From Gallery')),
            ),
          ],
        ),
      ),
    );
  }

  _pickFromGallery() async {
    PickedFile? image = await ImagePicker.platform
        .pickImage(source: ImageSource.gallery, imageQuality: 100);
     setState(() {
      _imagefile = File(image!.path);
    });
  }
}

Output

Pick image from gallery and camera in flutter
pick image from gallery and camera in flutter

Leave a Reply

Your email address will not be published. Required fields are marked *