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

Animated Navigation in Flutter

  Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition.   Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition. Table of Contents Project Setup Code Result Project Setup Before directly applying to your existing project, practice the code in some example projects. For this tutorial, we are going to name our project screen_animation_tutorial. Open in VSCode or Android Studio. After that, we will make two Screens. The first Screen will be the Starting screen and the next Screen will be the Final Screen. So go ahead and create two dart files under the lib folder. The main.dart file code should look like this Dart import 'package:flutter/material.dart'; import 'package:screen_animation_tutorial/start_screen.dart'; void ...

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) { ...

Flutter : Screen Animation tutorial

In this tutorial, we will learn how to perform animations while navigating from one screen to another. We will not require any other dependency to be installed. We will demonstrate the following example. So let's start. Approach Instead of using the default MaterialPageRoute, we will use the PageRouteBuilder. PageRouteBuilder provides all the functionalities like duration, type of animation. Syntax The syntax for PageRouteBuilder is as follows. PageRouteBuilder( transitionDuration: const Duration( seconds: 1 ), pageBuilder: (context, animation, secondaryAnimation) { return const SecondScreen(); }, ), The parameters and fields are self-explanatory. Code Let us code our First Screen of the app. class FirstScreen extends StatelessWidget { const FirstScreen({Key ? key}) : super ( key: key); @ override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "First...