camera 0.0.4

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 87

Camera Plugin

pub package

A Flutter plugin for iOS and Android allowing access to the device cameras.

Features:

  • Display live camera preview in a widget.
  • Snapshots can be captured and saved to a file.

Installation

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

iOS

Add a row to the ios/Runner/Info.plist of your app with the key Privacy - Camera Usage Description and a usage description.

Or in text format add the key:

<key>NSCameraUsageDescription</key>
<string>Can I use the camera please?</string>

Android

Change the minimum Android sdk version to 21 (or higher) in your android/app/build.gradle file.

minSdkVersion 21

Example

Here is a small example flutter app displaying a full screen camera preview.

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';

List<CameraDescription> cameras;

Future<Null> main() async {
  cameras = await availableCameras();
  runApp(new CameraApp());
}

class CameraApp extends StatefulWidget {
  @override
  _CameraAppState createState() => new _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  CameraController controller;

  @override
  void initState() {
    super.initState();
    controller = new CameraController(cameras[0], ResolutionPreset.medium);
    controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }

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

  @override
  Widget build(BuildContext context) {
    if (!controller.value.initialized) {
      return new Container();
    }
    return new AspectRatio(
        aspectRatio:
        controller.value.aspectRatio,
        child: new CameraPreview(controller));
  }
}

For a more elaborate usage example see here.

Note: This plugin is still under development, and some APIs might not be available yet. Feedback welcome and Pull Requests are most welcome!

0.0.4

  • Revert regression of CameraController.capture() introduced in v. 0.0.3.

0.0.3

  • Improved resource cleanup on Android. Avoids crash on Activity restart.
  • Made the Future returned by CameraController.dispose() and CameraController.capture() actually complete on Android.

0.0.2

  • Simplified and upgraded Android project template to Android SDK 27.
  • Moved Android package to io.flutter.plugins.
  • Fixed warnings from the Dart 2.0 analyzer.

0.0.1

  • Initial release

example/lib/main.dart

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

import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:path_provider/path_provider.dart';

class CameraExampleHome extends StatefulWidget {
  @override
  _CameraExampleHomeState createState() {
    return new _CameraExampleHomeState();
  }
}

IconData cameraLensIcon(CameraLensDirection direction) {
  switch (direction) {
    case CameraLensDirection.back:
      return Icons.camera_rear;
    case CameraLensDirection.front:
      return Icons.camera_front;
    case CameraLensDirection.external:
      return Icons.camera;
  }
  throw new ArgumentError('Unknown lens direction');
}

class _CameraExampleHomeState extends State<CameraExampleHome> {
  bool opening = false;
  CameraController controller;
  String imagePath;
  int pictureCount = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> headerChildren = <Widget>[];

    final List<Widget> cameraList = <Widget>[];

    if (cameras.isEmpty) {
      cameraList.add(const Text('No cameras found'));
    } else {
      for (CameraDescription cameraDescription in cameras) {
        cameraList.add(
          new SizedBox(
            width: 90.0,
            child: new RadioListTile<CameraDescription>(
              title: new Icon(cameraLensIcon(cameraDescription.lensDirection)),
              groupValue: controller?.description,
              value: cameraDescription,
              onChanged: (CameraDescription newValue) async {
                final CameraController tempController = controller;
                controller = null;
                await tempController?.dispose();
                controller =
                    new CameraController(newValue, ResolutionPreset.high);
                await controller.initialize();
                setState(() {});
              },
            ),
          ),
        );
      }
    }

    headerChildren.add(new Column(children: cameraList));
    if (controller != null) {
      headerChildren.add(playPauseButton());
    }
    if (imagePath != null) {
      headerChildren.add(imageWidget());
    }

    final List<Widget> columnChildren = <Widget>[];
    columnChildren.add(new Row(children: headerChildren));
    if (controller == null || !controller.value.initialized) {
      columnChildren.add(const Text('Tap a camera'));
    } else if (controller.value.hasError) {
      columnChildren.add(
        new Text('Camera error ${controller.value.errorDescription}'),
      );
    } else {
      columnChildren.add(
        new Expanded(
          child: new Padding(
            padding: const EdgeInsets.all(5.0),
            child: new Center(
              child: new AspectRatio(
                aspectRatio: controller.value.aspectRatio,
                child: new CameraPreview(controller),
              ),
            ),
          ),
        ),
      );
    }
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('Camera example'),
      ),
      body: new Column(children: columnChildren),
      floatingActionButton: (controller == null)
          ? null
          : new FloatingActionButton(
              child: const Icon(Icons.camera),
              onPressed: controller.value.isStarted ? capture : null,
            ),
    );
  }

  Widget imageWidget() {
    return new Expanded(
      child: new Align(
        alignment: Alignment.centerRight,
        child: new SizedBox(
          child: new Image.file(new File(imagePath)),
          width: 64.0,
          height: 64.0,
        ),
      ),
    );
  }

  Widget playPauseButton() {
    return new FlatButton(
      onPressed: () {
        setState(
          () {
            if (controller.value.isStarted) {
              controller.stop();
            } else {
              controller.start();
            }
          },
        );
      },
      child:
          new Icon(controller.value.isStarted ? Icons.pause : Icons.play_arrow),
    );
  }

  Future<Null> capture() async {
    if (controller.value.isStarted) {
      final Directory tempDir = await getTemporaryDirectory();
      if (!mounted) {
        return;
      }
      final String tempPath = tempDir.path;
      final String path = '$tempPath/picture${pictureCount++}.jpg';
      await controller.capture(path);
      if (!mounted) {
        return;
      }
      setState(
        () {
          imagePath = path;
        },
      );
    }
  }
}

List<CameraDescription> cameras;

Future<Null> main() async {
  cameras = await availableCameras();
  runApp(new MaterialApp(home: new CameraExampleHome()));
}

1. Depend on it

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


dependencies:
  camera: "^0.0.4"

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

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

3. Import it

Now in your Dart code, you can use:


import 'package:camera/camera.dart';
        
Version Uploaded Documentation Archive
0.0.4 Feb 13, 2018 Go to the documentation of camera 0.0.4 Download camera 0.0.4 archive
0.0.3 Feb 13, 2018 Go to the documentation of camera 0.0.3 Download camera 0.0.3 archive
0.0.2 Jan 11, 2018 Go to the documentation of camera 0.0.2 Download camera 0.0.2 archive
0.0.1 Jan 9, 2018 Go to the documentation of camera 0.0.1 Download camera 0.0.1 archive

Analysis

This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • tool failures on Feb 13, 2018
  • Dart: 2.0.0-dev.20.0
  • pana: 0.10.1
  • Flutter: 0.0.22

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
84 / 100
Health:
Code health derived from static analysis. [more]
100 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
76 / 100
Overall score:
Weighted score of the above. [more]
87

Platforms

Detected platforms: unsure

Error(s) prevent platform classification.

Suggestions

  • Fix dependencies in pubspec.yaml.

    Running flutter packages pub upgrade failed with the following output:

    ERR: Invalid argument(s): Minimum version ("2.0.0-dev.23.0") must be less than maximum ("2.0.0-dev.16.0").
    ERR: package:pub_semver/src/version_range.dart 59         new VersionRange
     package:pub/src/pubspec.dart 366                     Pubspec._ensureEnvironment
     package:pub/src/pubspec.dart 331                     Pubspec.dartSdkConstraint
     package:pub/src/solver/backtracking_solver.dart 511  BacktrackingSolver._checkPubspecMatchesSdkConstraint
     package:pub/src/solver/backtracking_solver.dart 474  BacktrackingSolver._checkVersion
     ===== asynchronous gap ===========================
     package:pub/src/solver/backtracking_solver.dart 432  BacktrackingSolver._findValidVersion.<fn>
     ===== asynchronous gap ===========================
     dart:async                                           Future.doWhile
     package:pub/src/solver/backtracking_solver.dart 430  BacktrackingSolver._findValidVersion
     package:pub/src/solver/backtracking_solver.dart 337  BacktrackingSolver._versionQueueFor
     ===== asynchronous gap ===========================
     package:pub/src/solver/backtracking_solver.dart 290  BacktrackingSolver._solve.<fn>
     ===== asynchronous gap ===========================
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/backtracking_solver.dart 315  BacktrackingSolver._solve.<fn>
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/version_selection.dart 64     VersionSelection.select
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/version_selection.dart 91     VersionSelection._addDependencies
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/version_selection.dart 91     VersionSelection._addDependencies
    ERR: This is an unexpected error. Please run
     
         pub --trace upgrade --verbosity io --no-precompile
     
     and include the logs in an issue on https://github.com/dart-lang/pub/issues/new
    
  • Fix platform conflicts.

    Make sure none of the libraries use mutually exclusive dependendencies.

  • Fix issues reported by dartanalyzer.

    dartanalyzer reported 1 error(s) and 0 warning(s).

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <2.0.0