How to pick image from gallery in Flutter? – image_picker

In this post, you will learn how to pick an image from the gallery in a flutter app. You will also learn how to open the camera from a flutter app to capture a photo and show it in the app. I will use a plugin called image_picker to pick an image from the gallery or to capture a photo.

About image_picker from the official doc:

A Flutter plugin for iOS and Android for picking images from the image library and taking new pictures with the camera.

How to pick image from gallery in flutter?

if you have already set up a new flutter project, you first need to add the image_picker dependency to the project’s pubspec.yaml file. To do this, open pubspec.yaml file and add the below code to it.

dependencies:
  flutter:
    sdk: flutter
  image_picker: ^0.8.5+3

Open main.dart file and import the image_picker.

import 'package:image_picker/image_picker.dart';

We use the ImagePicker.pickImage() method to pick an image from the gallery or to capture a photo. This method returns an instance of XFile. I will use the XFile instance to get the path of the image.

Get the instance of ImagePicker:

var imagePicker;
 @override
  void initState() {
    super.initState();
    //Get the ImagePicker instance
    imagePicker = ImagePicker();
  }

To capture a photo:

imagePicker.pickImage(source: ImageSource.camera)

To pick image from the gallery:

imagePicker.pickImage(
source: ImageSource.gallery)

Now, let’s see the full code.

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'image_picker Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'image_picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  var _image;
  var imagePicker;

  @override
  void initState() {
    super.initState();
    //Get the ImagePicker instance
    imagePicker = ImagePicker();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
          _image != null
              ? Image.file(
                  _image,
                  width: 300,
                  height: 300,
                )
              : Image.network(
                  "https://via.placeholder.com/300x300.png?text=Select or capture an image"),
          SizedBox(height: 20),
          Row(mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () async {
                    XFile? image =
                        await imagePicker.pickImage(source: ImageSource.camera);
                    setState(() {
                      if (image != null) {
                        _image = File(image.path);
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text("No image Selected")));
                      }
                    });
                  },
                  child: Text("Capture photo")),
              SizedBox(
                width: 8,
              ),
              ElevatedButton(
                  onPressed: () async {
                    //ImagePicker.pickImage() method returns XFile instance
                    //that we can use to get the path of the image.
                    XFile? image = await imagePicker.pickImage(
                        source: ImageSource.gallery);
                    setState(() {
                      if (image != null) {
                        _image = File(image.path);
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text("No image Selected")));
                      }
                    });
                  },
                  child: Text("Open Gallery"))
            ],
          )
        ]),
      ),
    );
  }
}

Here, I used two buttons. When you press the first button it opens the camera to capture a photo. And when you press the second button it opens the gallery to pick an image.

Output:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: