How to select an image in Flutter

How to select an image in Flutter

In this guide, we will discuss how to select an image in Flutter. For this, we are using the additional package/plugin of the flutter i.e file picker.

At First, we should add the dependency on the pubspec.yaml file which is given below

dependencies:
  flutter:
    sdk: flutter

  file_picker: ^4.5.1

If we’re using VS Code, it will automatically pull in  file_picker once you save the pubspec.yaml file. If we’re not using VS Code run the following command to pull in the latest added dependency:

flutter pub get

This Package allows you to use the native file explorer to pick single or multiple files, with extensions filtering support.

for Picking a Single file we have

FilePickerResult? result = await FilePicker.platform.pickFiles();

if (result != null) {
  File file = File(result.files.single.path);
} else {
  // User canceled the picker
}

for Picking multiple files we have

FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

if (result != null) {
  List<File> files = result.paths.map((path) => File(path)).toList();
} else {
  // User canceled the picker
}

for Multiple files with an extension filter we have

FilePickerResult? result = await FilePicker.platform.pickFiles(
  type: FileType.custom,
  allowedExtensions: ['jpg', 'pdf', 'doc'],
);

Let’s take an example of how we can select an image with the help of the file_picker plugin in our flutter application.

import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

  @override
  State<ImagePickerScreen> createState() => _ImagePickerScreenState();
}

class _ImagePickerScreenState extends State<ImagePickerScreen> {
  File? image;

  Future pickImage() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['jpg', 'png', 'jpeg'],
      );

      if (result != null) {
        final file = File(result.files.single.path!);
        setState(() {
          image = file;
        });
      } else {
        return;
      }
    } on PlatformException catch (e) {
      debugPrint('Failed to pick image: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Picker in Flutter'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              pickImage();
            },
            child: const Text('Pick Image'),
          ),
          Center(
              child: image == null
                  ? const Text('No Image')
                  : Image.file(
                      image!,
                      height: 400,
                    )),
        ],
      ),
    );
  }
}

In the above example, We render the Image.file based on the condition of the image variable. If the image is not null or undefined, then we know it has an image then we render the Image.file widget bypassing the _image variable to it. The Image.file is a widget that is used to render images from the local storage of a device. If there is nothing in the image variable, we render the Text widget with No image.

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

If we click the “Pick Image” button, It will navigate to select the image on the next screen which is shown below

After selecting any one of the images from here It will reflect back to the app and show an image downward the button which is shown below

Thank you for reading the Guide on How to Select the Image in Flutter.

Also read: How To Implement Onboarding Screen PageView In Flutter