0
0
FlutterHow-ToBeginner · 3 min read

How to Use image_picker in Flutter: Simple Guide

To use image_picker in Flutter, add it to your pubspec.yaml, import it, then call ImagePicker().pickImage() to select an image from the gallery or camera. The picked image returns a XFile which you can display using Image.file().
📐

Syntax

The main method to pick an image is pickImage() from the ImagePicker class. It takes a required source parameter to specify if the image is from the camera or gallery.

  • source: Use ImageSource.camera or ImageSource.gallery.
  • imageQuality: Optional, to reduce image size (0-100).
  • maxWidth, maxHeight: Optional, to resize the image.

The method returns a Future<XFile?> which is the selected image file or null if cancelled.

dart
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(
  source: ImageSource.gallery,
  imageQuality: 80,
  maxWidth: 600,
  maxHeight: 600,
);
💻

Example

This example shows a simple Flutter app with a button to pick an image from the gallery and display it on screen.

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  XFile? _image;
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _image = image;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Image Picker Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _image == null
                  ? Text('No image selected.')
                  : Image.file(File(_image!.path), width: 200, height: 200),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _pickImage,
                child: Text('Pick Image from Gallery'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Output
A screen with a button labeled 'Pick Image from Gallery'. When tapped, it opens the gallery. After selecting an image, the image appears centered on the screen above the button.
⚠️

Common Pitfalls

  • Not adding image_picker to pubspec.yaml dependencies.
  • Forgetting to add required permissions in AndroidManifest.xml (camera, storage) and Info.plist (iOS).
  • Not handling the case when user cancels image picking (null result).
  • Using Image.file without importing dart:io.
dart
/// Wrong: Not checking for null
final XFile? image = await picker.pickImage(source: ImageSource.camera);
// This can cause error if user cancels

/// Right: Check for null
final XFile? image = await picker.pickImage(source: ImageSource.camera);
if (image != null) {
  // use image
}
📊

Quick Reference

  • pickImage(source): Pick image from camera or gallery.
  • pickVideo(source): Pick video similarly.
  • XFile.path: File path of picked media.
  • Permissions: Add camera and storage permissions in platform files.

Key Takeaways

Add image_picker to pubspec.yaml and import it before use.
Use ImagePicker().pickImage() with source to pick images from gallery or camera.
Always check if the returned XFile is null to handle user cancellation.
Add necessary permissions in AndroidManifest.xml and Info.plist for camera and gallery access.
Display picked images using Image.file with dart:io File from XFile.path.