Skip to main content

Flutter : Image Picker Tutorial | Pick single image from Gallery

Introduction

In this tutorial, we will create an image picker and display the content on the screen. Image Picker picks a file from the Storage or Camera and stores it in an XFile object.

Implementation

Install dependency

We will first need the image_picker dependency.
To install it, add the following dependency to pubspec.yaml file.
image_picker: ^0.8.4+3
Then click on Get Packages in your IDE or run the following command on your Terminal / Command Prompt.
flutter pub get

Example

Import the dependency in your dart file.

import 'package:image_picker/image_picker.dart';

Syntax

Image picking is a future task. So we need to await the image picking. Here is the syntax.
await _picker.pickImage(source: ImageSource.gallery);

Here we have provided the source from the gallery. We can also provide the source as a Camera using the following syntax.
await _picker.pickImage(source: ImageSource.camera);

Also, the image is stored in a file type of Xfile. Later we modify it to a convenient file type of our choice. In our example, we will store it in a File object and then display it using the Image.file() widget.
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

Demo

Here is a demo code. In this code, when the user presses the button, the image picker opens the Gallery. Then if we choose an image, it will display the image on the screen. Else it will be blank as previously.
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);

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

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

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

class _ImagePickerTutorialState extends State<ImagePickerTutorial> {
  File? pickedImage;
  bool isPicked = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Image Picker"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Container(
                child: isPicked
                    ? Image.file(
                        pickedImage!,
                        width: MediaQuery.of(context).size.width,
                        height: MediaQuery.of(context).size.width * (4 / 3),
                      )
                    : Container(
                        color: Colors.blueGrey[100],
                        width: MediaQuery.of(context).size.width,
                        height: MediaQuery.of(context).size.width * (4 / 3),
                      ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(48.0),
              child: ElevatedButton(
                onPressed: () async {
                  final ImagePicker _picker = ImagePicker();
                  final XFile? image =
                      await _picker.pickImage(source: ImageSource.gallery);
                  if (image != null) {
                    pickedImage = File(image.path);
                    setState(() {
                      isPicked = true;
                    });
                  }
                },
                child: const Text("Pick Image"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Output 



Summary

  • We learned to pick an image in Flutter
  • Used image_picker plugin.



Comments

  1. You have accomplished extraordinary work by distributing this article here. It is valuable and advantageous information for us. It's Really helpful for Mobile app development, Continue to update our insight by share these sorts of articles.

    ReplyDelete

Post a Comment

If you have any problem or doubt please comment.

Popular posts from this blog

Flutter | Material Banner Tutorial

In this tutorial, we will create and display Material Banner in Flutter . Material Banners are displayed at the top of the screen . User interaction is required to dismiss the banner . Material Banner Material Banner alerts the user about action and p rovides some actions for the user to take . In brief, it alerts the user about an issue and the user address the issue . The user should dismiss the banner to remove it from the screen else it will be active. Syntax  ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: content, actions: actions)) Code Here is our starting class. It is a stateless class and we will display a banner when the Button is pressed. class SnackBarTutorial extends StatelessWidget { const SnackBarTutorial({Key ? key}) : super ( key: key); @ override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Material Banner"

How to create Snackbars in Flutter | Snackbar Tutorial

In this article, we will create and display different types of SnackBars in Flutter.  SnackBars in Flutter SnackBars are used to briefly display some information or inform the user about an action. For instance, when a user deletes a mail or message you may want to inform the user about the action. Also, the user can undo the action he performed by the undo button in the Snackbar . Syntax For creating a SnackBar, we use the following code. ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: content)); Inside the content field of SnackBar, we will pass the content. Any content can be passed inside it, but in practice, small messages with or without a button. Example Simple SnackBar class SnackBarTutorial extends StatelessWidget {   const SnackBarTutorial({Key? key}) : super (key: key);   @override   Widget build(BuildContext context) {     return

Flutter: DatePicker Tutorial both with Material and Cupertino Style

Introduction DatePicker is very important when you want the user to pick his / her date of birth or something else. In Flutter, implementing DatePicker is very easy and we will implement DatePicker in both Android or Material style and Cupertino or IOS style.  Table of contents Approach Project Setup Material Style DatePicker Cupertino Style DatePicker Conclusion Approach Flutter has widgets for everything and even for DatePicker. DatePicker widget is loaded with all needed animation and colours. So implementation is very easy.  Project Setup No extra plugins are required for this project and you can continue with your existing project. Here is the starting code. class DatePickerTutorial extends StatefulWidget { const DatePickerTutorial({Key? key}) : super (key: key); @ override _DatePickerTutorialState createState() => _DatePickerTutorialState(); } class _DatePickerTutorialState extends State<DatePick