better_image_picker 0.6.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 67

Image Picker plugin for Flutter #

pub package

A Flutter plugin for iOS and Android for picking images from the image library, and taking new pictures with the camera.

Installation #

First, add image_picker as a dependency in your pubspec.yaml file.

iOS #

Add the following keys to your Info.plist file, located in <project root>/ios/Runner/Info.plist:

  • NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
  • NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
  • NSMicrophoneUsageDescription - describe why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor.

Android #

No configuration required - the plugin should work out of the box.

Example #

import 'package:image_picker/image_picker.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Example'),
      ),
      body: Center(
        child: _image == null
            ? Text('No image selected.')
            : Image.file(_image),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }
}

Handling MainActivity destruction on Android #

Android system -- although very rarely -- sometimes kills the MainActivity after the image_picker finishes. When this happens, we lost the data selected from the image_picker. You can use retrieveLostData to retrieve the lost data in this situation. For example:

Future<void> retrieveLostData() async {
  final LostDataResponse response =
      await ImagePicker.retrieveLostData();
  if (response == null) {
    return;
  }
  if (response.file != null) {
    setState(() {
      if (response.type == RetrieveType.video) {
        _handleVideo(response.file);
      } else {
        _handleImage(response.file);
      }
    });
  } else {
    _handleError(response.exception);
  }
}

There's no way to detect when this happens, so calling this method at the right place is essential. We recommend to wire this into some kind of start up check. Please refer to the example app to see how we used it.

0.6.3+2 #

  • Bump RoboElectric dependency to 4.3.1 and update resource usage.

0.6.3+1 #

  • Fix an issue that the example app won't launch the image picker after Android V2 embedding migration.

0.6.3 #

  • Support Android V2 embedding.
  • Migrate to using the new e2e test binding.

0.6.2+3 #

  • Remove the deprecated author: field from pubspec.yaml
  • Migrate the plugin to the pubspec platforms manifest.
  • Require Flutter SDK 1.10.0 or greater.

0.6.2+2 #

  • Android: Revert the image file return logic when the image doesn't have to be scaled. Fix a rotation regression caused by 0.6.2+1
  • Example App: Add a dialog to enter maxWidth, maxHeight or quality when picking image.

0.6.2+1 #

  • Android: Fix a crash when a non-image file is picked.
  • Android: Fix unwanted bitmap scaling.

0.6.2 #

  • iOS: Fixes an issue where picking content from Gallery would result in a crash on iOS 13.

0.6.1+11 #

  • Stability and Maintainability: update documentations, add unit tests.

0.6.1+10 #

  • iOS: Fix image orientation problems when scaling images.

0.6.1+9 #

  • Remove AndroidX warning.

0.6.1+8 #

  • Fix iOS build and analyzer warnings.

0.6.1+7 #

  • Android: Fix ImagePickerPlugin#onCreate casting context which causes exception.

0.6.1+6 #

  • Define clang module for iOS

0.6.1+5 #

  • Update and migrate iOS example project.

0.6.1+4 #

  • Android: Fix a regression where the retrieveLostImage does not work anymore.
  • Set up Android unit test to test ImagePickerCache and added image quality caching tests.

0.6.1+3 #

  • Bugfix iOS: Fix orientation of the picked image after scaling.
  • Remove unnecessary code that tried to normalize the orientation.
  • Trivial XCTest code fix.

0.6.1+2 #

  • Replace dependency on androidx.legacy:legacy-support-v4:1.0.0 with androidx.core:core:1.0.2

0.6.1+1 #

  • Add dependency on androidx.annotation:annotation:1.0.0.

0.6.1 #

  • New feature : Get images with custom quality. While picking images, user can pass imageQuality parameter to compress image.

0.6.0+20 #

  • Android: Migrated information cache methods to use instance methods.

0.6.0+19 #

  • Android: Fix memory leak due not unregistering ActivityLifecycleCallbacks.

0.6.0+18 #

  • Fix video play in example and update video_player plugin dependency.

0.6.0+17 #

  • iOS: Fix a crash when user captures image from the camera with devices under iOS 11.

0.6.0+16 #

  • iOS Simulator: fix hang after trying to take an image from the non-existent camera.

0.6.0+15 #

  • Android: throws an exception when permissions denied instead of ignoring.

0.6.0+14 #

  • Fix typo in README.

0.6.0+13 #

  • Bugfix Android: Fix a crash occurs in some scenarios when user picks up image from gallery.

0.6.0+12 #

  • Use class instead of struct for GIFInfo in iOS implementation.

0.6.0+11 #

  • Don't use module imports.

0.6.0+10 #

  • iOS: support picking GIF from gallery.

0.6.0+9 #

  • Add missing template type parameter to invokeMethod calls.
  • Bump minimum Flutter version to 1.5.0.
  • Replace invokeMethod with invokeMapMethod wherever necessary.

0.6.0+8 #

  • Bugfix: Add missed return statement into the image_picker example.

0.6.0+7 #

  • iOS: Rename objects to follow Objective-C naming convention to avoid conflicts with other iOS library/frameworks.

0.6.0+6 #

  • iOS: Picked image now has all the correct meta data from the original image, includes GPS, orientation and etc.

0.6.0+5 #

  • iOS: Add missing import.

0.6.0+4 #

  • iOS: Using first byte to determine original image type.
  • iOS: Added XCTest target.
  • iOS: The picked image now has the correct EXIF data copied from the original image.

0.6.0+3 #

  • Android: fixed assertion failures due to reply messages that were sent on the wrong thread.

0.6.0+2 #

  • Android: images are saved with their real extension instead of always using .jpg.

0.6.0+1 #

  • Android: Using correct suffix syntax when picking image from remote url.

0.6.0 #

  • Breaking change iOS: Returned File objects when picking videos now always holds the correct path. Before this change, the path returned could have file:// prepended to it.

0.5.4+3 #

  • Fix the example app failing to load picked video.

0.5.4+2 #

  • Request Camera permission if it present in Manifest on Android >= M.

0.5.4+1 #

  • Bugfix iOS: Cancel button not visible in gallery, if camera was accessed first.

0.5.4 #

  • Add retrieveLostData to retrieve lost data after MainActivity is killed.

0.5.3+2 #

  • Android: fix a crash when the MainActivity is destroyed after selecting the image/video.

0.5.3+1 #

  • Update minimum deploy iOS version to 8.0.

0.5.3 #

  • Fixed incorrect path being returned from Google Photos on Android.

0.5.2 #

  • Check iOS camera authorizationStatus and return an error, if the access was denied.

0.5.1 #

  • Android: Do not delete original image after scaling if the image is from gallery.

0.5.0+9 #

  • Remove unnecessary temp video file path.

0.5.0+8 #

  • Fixed wrong GooglePhotos authority of image Uri.

0.5.0+7 #

  • Fix a crash when selecting images from yandex.disk and dropbox.

0.5.0+6 #

  • Delete the original image if it was scaled.

0.5.0+5 #

  • Remove unnecessary camera permission.

0.5.0+4 #

  • Preserve transparency when saving images.

0.5.0+3 #

  • Fixed an Android crash when Image Picker is registered without an activity.

0.5.0+2 #

  • Log a more detailed warning at build time about the previous AndroidX migration.

0.5.0+1 #

  • Fix a crash when user calls the plugin in quick succession on Android.

0.5.0 #

  • Breaking change. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to also migrate if they're using the original support library.

0.4.12+1 #

  • Fix a crash when selecting downloaded images from image picker on certain devices.

0.4.12 #

  • Fix a crash when user tap the image mutiple times.

0.4.11 #

  • Use api to define support-v4 dependency to allow automatic version resolution.

0.4.10 #

  • Depend on full support-v4 library for ease of use (fixes conflicts with Firebase and libraries)

0.4.9 #

  • Bugfix: on iOS prevent to appear one pixel white line on resized image.

0.4.8 #

  • Replace the full com.android.support:appcompat-v7 dependency with com.android.support:support-core-utils, which results in smaller APK sizes.
  • Upgrade support library to 27.1.1

0.4.7 #

  • Added missing video_player package dev dependency.

0.4.6 #

  • Added support for picking remote images.

0.4.5 #

  • Bugfixes, code cleanup, more test coverage.

0.4.4 #

  • Updated Gradle tooling to match Android Studio 3.1.2.

0.4.3 #

  • Bugfix: on iOS the pickVideo method will now return null when the user cancels picking a video.

0.4.2 #

  • Added support for picking videos.
  • Updated example app to show video preview.

0.4.1 #

  • Bugfix: the pickImage method will now return null when the user cancels picking the image, instead of hanging indefinitely.
  • Removed the third party library dependency for taking pictures with the camera.

0.4.0 #

  • Breaking change. The source parameter for the pickImage is now required. Also, the ImageSource.any option doesn't exist anymore.
  • Use the native Android image gallery for picking images instead of a custom UI.

0.3.1 #

  • Bugfix: Android version correctly asks for runtime camera permission when using ImageSource.camera.

0.3.0 #

  • Breaking change. Set SDK constraints to match the Flutter beta release.

0.2.1 #

  • Simplified and upgraded Android project template to Android SDK 27.
  • Updated package description.

0.2.0 #

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here.

0.1.5 #

  • Added FLT prefix to iOS types

0.1.4 #

  • Bugfix: canceling image picking threw exception.
  • Bugfix: errors in plugin state management.

0.1.3 #

  • Added optional source argument to pickImage for controlling where the image comes from.

0.1.2 #

  • Added optional maxWidth and maxHeight arguments to pickImage.

0.1.1 #

  • Updated Gradle repositories declaration to avoid the need for manual configuration in the consuming app.

0.1.0+1 #

  • Updated readme and description in pubspec.yaml

0.1.0 #

  • Updated dependencies
  • Breaking Change: You need to add a maven section with the "https://maven.google.com" endpoint to the repository section of your android/build.gradle. For example:
allprojects {
    repositories {
        jcenter()
        maven {                              // NEW
            url "https://maven.google.com"   // NEW
        }                                    // NEW
    }
}

0.0.3 #

  • Fix for crash on iPad when showing the Camera/Gallery selection dialog

0.0.2+2 #

  • Updated README

0.0.2+1 #

  • Updated README

0.0.2 #

  • Fix crash when trying to access camera on a device without camera (e.g. the Simulator)

0.0.1 #

  • Initial Release

example/lib/main.dart

// Copyright 2019 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/basic.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:better_image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Picker Demo',
      home: MyHomePage(title: 'Image Picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  File _imageFile;
  dynamic _pickImageError;
  bool isVideo = false;
  VideoPlayerController _controller;
  String _retrieveDataError;

  final TextEditingController maxWidthController = TextEditingController();
  final TextEditingController maxHeightController = TextEditingController();
  final TextEditingController qualityController = TextEditingController();

  Future<void> _playVideo(File file) async {
    if (file != null && mounted) {
      await _disposeVideoController();
      _controller = VideoPlayerController.file(file);
      await _controller.setVolume(1.0);
      await _controller.initialize();
      await _controller.setLooping(true);
      await _controller.play();
      setState(() {});
    }
  }

  void _onImageButtonPressed(ImageSource source, {BuildContext context}) async {
    if (_controller != null) {
      await _controller.setVolume(0.0);
    }
    if (isVideo) {
      final File file = await ImagePicker.pickVideo(source: source);
      await _playVideo(file);
    } else {
      await _displayPickImageDialog(context,
          (double maxWidth, double maxHeight, int quality) async {
        try {
          _imageFile = await ImagePicker.pickImage(
              source: source,
              maxWidth: maxWidth,
              maxHeight: maxHeight,
              imageQuality: quality);
          setState(() {});
        } catch (e) {
          _pickImageError = e;
        }
      });
    }
  }

  @override
  void deactivate() {
    if (_controller != null) {
      _controller.setVolume(0.0);
      _controller.pause();
    }
    super.deactivate();
  }

  @override
  void dispose() {
    _disposeVideoController();
    maxWidthController.dispose();
    maxHeightController.dispose();
    qualityController.dispose();
    super.dispose();
  }

  Future<void> _disposeVideoController() async {
    if (_controller != null) {
      await _controller.dispose();
      _controller = null;
    }
  }

  Widget _previewVideo() {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_controller == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    }
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: AspectRatioVideo(_controller),
    );
  }

  Widget _previewImage() {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_imageFile != null) {
      return Image.file(_imageFile);
    } else if (_pickImageError != null) {
      return Text(
        'Pick image error: $_pickImageError',
        textAlign: TextAlign.center,
      );
    } else {
      return const Text(
        'You have not yet picked an image.',
        textAlign: TextAlign.center,
      );
    }
  }

  Future<void> retrieveLostData() async {
    final LostDataResponse response = await ImagePicker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      if (response.type == RetrieveType.video) {
        isVideo = true;
        await _playVideo(response.file);
      } else {
        isVideo = false;
        setState(() {
          _imageFile = response.file;
        });
      }
    } else {
      _retrieveDataError = response.exception.code;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Platform.isAndroid
            ? FutureBuilder<void>(
                future: retrieveLostData(),
                builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                    case ConnectionState.waiting:
                      return const Text(
                        'You have not yet picked an image.',
                        textAlign: TextAlign.center,
                      );
                    case ConnectionState.done:
                      return isVideo ? _previewVideo() : _previewImage();
                    default:
                      if (snapshot.hasError) {
                        return Text(
                          'Pick image/video error: ${snapshot.error}}',
                          textAlign: TextAlign.center,
                        );
                      } else {
                        return const Text(
                          'You have not yet picked an image.',
                          textAlign: TextAlign.center,
                        );
                      }
                  }
                },
              )
            : (isVideo ? _previewVideo() : _previewImage()),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () {
              isVideo = false;
              _onImageButtonPressed(ImageSource.gallery, context: context);
            },
            heroTag: 'image0',
            tooltip: 'Pick Image from gallery',
            child: const Icon(Icons.photo_library),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(ImageSource.camera, context: context);
              },
              heroTag: 'image1',
              tooltip: 'Take a Photo',
              child: const Icon(Icons.camera_alt),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.gallery);
              },
              heroTag: 'video0',
              tooltip: 'Pick Video from gallery',
              child: const Icon(Icons.video_library),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.camera);
              },
              heroTag: 'video1',
              tooltip: 'Take a Video',
              child: const Icon(Icons.videocam),
            ),
          ),
        ],
      ),
    );
  }

  Text _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }

  Future<void> _displayPickImageDialog(
      BuildContext context, OnPickImageCallback onPick) async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Add optional parameters'),
            content: Column(
              children: <Widget>[
                TextField(
                  controller: maxWidthController,
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  decoration:
                      InputDecoration(hintText: "Enter maxWidth if desired"),
                ),
                TextField(
                  controller: maxHeightController,
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  decoration:
                      InputDecoration(hintText: "Enter maxHeight if desired"),
                ),
                TextField(
                  controller: qualityController,
                  keyboardType: TextInputType.number,
                  decoration:
                      InputDecoration(hintText: "Enter quality if desired"),
                ),
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('CANCEL'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                  child: const Text('PICK'),
                  onPressed: () {
                    double width = maxWidthController.text.isNotEmpty
                        ? double.parse(maxWidthController.text)
                        : null;
                    double height = maxHeightController.text.isNotEmpty
                        ? double.parse(maxHeightController.text)
                        : null;
                    int quality = qualityController.text.isNotEmpty
                        ? int.parse(qualityController.text)
                        : null;
                    onPick(width, height, quality);
                    Navigator.of(context).pop();
                  }),
            ],
          );
        });
  }
}

typedef void OnPickImageCallback(
    double maxWidth, double maxHeight, int quality);

class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

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

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller.value.initialized) {
      initialized = controller.value.initialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller.addListener(_onVideoControllerUpdate);
  }

  @override
  void dispose() {
    controller.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller.value?.aspectRatio,
          child: VideoPlayer(controller),
        ),
      );
    } else {
      return Container();
    }
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  better_image_picker: ^0.6.4

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:better_image_picker/image_picker.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
34
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
67
Learn more about scoring.

We analyzed this package on Jul 9, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because:

  • package:better_image_picker/image_picker.dart that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because:

  • package:better_image_picker/image_picker.dart that declares support for platforms: android, ios

Package does not support Flutter platform web

Because:

  • package:better_image_picker/image_picker.dart that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because:

  • package:better_image_picker/image_picker.dart that declares support for platforms: android, ios

Package not compatible with SDK dart

Because:

  • better_image_picker that is a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
flutter_plugin_android_lifecycle ^1.0.2 1.0.8
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.1
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
e2e ^0.2.1
flutter_test
video_player ^0.10.3