Skip to content

[Flutter] How to Use the Camera to Take Pictures and Display Picture

Last Updated on 2021-10-20 by Clay

If we want to call the phone camera to take a picture and display the pictures on the screen is not so difficult in Flutter project. In fact, the real challenge is to store photos in the phone's album, or even create a cropped photo function.

This article is based on the official Flutter teaching document to record how to use the camera in the Flutter project.


Preparation

Step 1: Add dependencies

Before we using phone camera, we need to add the dependences into pubspec.yaml file.

  • camera: Provide tools related to camera
  • path_provider: Find the correct path to save photos
  • path: Build a path that works on any platform
dependencies:
  flutter:
    sdk: flutter
  camera:
  path_provider:
  path:




Step 2: Setting for different platforms

If you are on the Android platform, you need to confirm that minSdkVersion is 21 or higher. (You can refer here: [Solved][Flutter] Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [:camera])

And you need to add the setting into ios/Runner/Info.plist on iOS system:

<key>NSCameraUsageDescription</key>
<string>Explanation on why the camera access is needed.</string>

Sample Code

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

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


Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Obtain a list of available cameras
  final cameras = await availableCameras();

  // Get a specific camera (first one)
  final firstCamera = cameras.first;

  runApp(
    MaterialApp(
      home: TakePicturePage(
        camera: firstCamera,
      )
    )
  );
}


// Take picture page
class TakePicturePage extends StatefulWidget {
  final CameraDescription camera;

  const TakePicturePage({
    Key key,
    @required this.camera,
  }) : super(key: key);

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


// Take picture page state
class TakePicturePageState extends State<TakePicturePage> {
  CameraController _controller;
  Future<void> _initializeControllerFuture;

  @override
  void initState() {
    // Init
    super.initState();
    _controller = CameraController(
      // Camera settings
      widget.camera,
      ResolutionPreset.max,
    );

    // Initialize the controller
    _initializeControllerFuture = _controller.initialize();
  }

  // Dispose of the controller when the widget is disposed
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Take a picture demo")
      ),
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return CameraPreview(_controller);
          }
          else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),

      floatingActionButton: Container(
        height: 75.0,
        width: 75.0,
        child: FittedBox(
          child: FloatingActionButton(
              backgroundColor: Colors.white,
              child: Icon(
                Icons.camera_alt_rounded,
                color: Colors.black,
              ),
              onPressed: () async {
                try {
                  await _initializeControllerFuture;
                  final image = await _controller.takePicture();

                  // If the picture was taken
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => DisplayPicturePage(
                        imagePath: image?.path,
                      ),
                    ),
                  );

                  print("My Image Path:");
                  print(image?.path);
                }
                catch (error) {
                  print(error);
                }
              }
          ),
        ),
      ),

      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}


// A new page for displaying the picture
class DisplayPicturePage extends StatelessWidget {
  final String imagePath;
  const DisplayPicturePage({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Display the picture")
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text("$imagePath"),
            Container(
              width: MediaQuery.of(context).size.width/2,
              height: MediaQuery.of(context).size.height/2,
              child: Image.file(File(imagePath)),
            ),
          ],
        )
      )
    );
  }
}



Output:

Take a picture
display the picture

It can be seen from the path above the picture that the photos taken by this method are not stored in the photo library of the mobile phone, but placed in the cache.

Okay, the above is how to use the phone camera to take a picture in the Flutter application.


References


Read More

Tags:

Leave a Reply