How to use image_picker in Flutter

In Flutter app development, incorporating features to select images from the device’s gallery or capture new ones via the camera is a common requirement. Thankfully, Flutter provides an elegant solution for this through the image_picker plugin.

First ensure you have Flutter installed on your system and a basic understanding of Flutter app development.

Step 1: Adding the Dependency
Begin by updating your pubspec.yaml file to include the image_picker dependency:

dependencies:
  flutter:
    sdk: flutter
  image_picker: ^1.0.7  # (ensure to use the latest version)

After adding the dependency, execute flutter pub get in your terminal to install the plugin.

Step 2: Importing the Package
Import the image_picker package in the Dart file where you intend to utilize it:

import 'package:image_picker/image_picker.dart';

Step 3: Implementing Image Selection
Let’s proceed to implement image selection functionality for both the gallery and the camera.

Selecting Image from Gallery:

Future<void> _getImageFromGallery() async {
  final XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.gallery,
  );

  if (pickedFile != null) {
    // Handle the picked image file
    setState(() {
      _imageFile = File(pickedFile.path);
    });
  }
}

Capturing Image from Camera:

Future<void> _captureImageFromCamera() async {
  final XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.camera,
  );

  if (pickedFile != null) {
    // Handle the captured image file
    setState(() {
      _imageFile = File(pickedFile.path);
    });
  }
}

In the above snippets, _imageFile represents a File variable where the selected image is stored for further processing.

Step 4: UI Integration
Integrate the image selection functions with your UI. For instance, trigger _getImageFromGallery() when users tap a button to select an image from the gallery, and _captureImageFromCamera() when they wish to capture an image using the camera.


ElevatedButton(
  onPressed: _getImageFromGallery,
  child: Text('Select Image from Gallery'),
),
ElevatedButton(
  onPressed: _captureImageFromCamera,
  child: Text('Capture Image from Camera'),
),

Check out these:

How to use image_picker in Flutter

Resolving the “laravel/ui Package” Error in Laravel Authentication

Improving Flutter Code Quality with flutter analyze

What is Flutter?

Intel HAXM Installation Failed in Android Studio Emulator

Leave a Comment