Build a camera application internal camera

Posted by Zag0r on Sat, 22 Jan 2022 23:15:41 +0100

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-kz87r0is-1625531278584)( https://ducafecat.tech/2021/07/06/translation/build-a-camera-app-flutter-in-app-camera/2021-07-06-08-18-54.png )]

Old iron remember to forward, brother old fellow will show more Flutter good text ~ ~ ~

Wechat group ducafecat

Station b https://space.bilibili.com/404904528

original text

https://medium.com/geekculture/build-a-camera-app-flutter-in-app-camera-825b829fe138

code

https://github.com/jagrut-18/flutter_camera_app.git

reference resources

  • https://pub.dev/packages/camera

text

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-6dflhcck-1625531278585)( https://ducafecat.tech/2021/07/06/translation/build-a-camera-app-flutter-in-app-camera/2021-07-06-08-03-41.png )]

In many applications, we need users to upload pictures by clicking on them. For this purpose, we can use the default camera application of the device, but what if we need to integrate the camera within an application? Well, this is also possible, Flutter. The team has developed a camera https://pub.dev/packages/camera , it allows us to do this.

Build project

First, in pubspec Add the following line to the yaml file to install the camera package into the project.

camera: ^0.8.1+3
  • IOS settings

This plug-in requires IOS 10.0 or later. In info Add the following line to the plist file to set the content.

<key>NSCameraUsageDescription</key>
<string>Can I use the camera please?</string>
<key>NSMicrophoneUsageDescription</key>
<string>Can I use the mic please?</string>
  • Android Setup

In Android / APP / build Change the Android sdk minimum version to 21 (or higher) in the gradle file.

minSdkVersion 21

Now that our project setup is complete, we can start writing the application.

We will create two screens in the application.

1.CameraScreen - this screen will display the camera output and take pictures

2.GalleryScreen - this screen will display the captured image in the grid view.

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qjtyvdg5-1625531278586)( https://ducafecat.tech/2021/07/06/translation/build-a-camera-app-flutter-in-app-camera/2021-07-06-08-05-53.png )]

Load camera

In order to display the camera preview, we need to load the camera first. To do this, go to main The main function in the dart file and the lines above runApp.

WidgetsFlutterBinding.ensureInitialized(); //Ensure plugin services are initializedfinal cameras = await availableCameras(); //Get list of available cameras

Now that we have a list of cameras, we need to pass them to our camera / screen.

So the camera will pass like this

After all this, this is main Dart.

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Obtain a list of the available cameras on the device.
  final cameras = await availableCameras();
  runApp(MyApp(cameras: cameras));
}

class MyApp extends StatelessWidget {
  final List<CameraDescription> cameras;
  const MyApp({Key? key, required this.cameras}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Camera App',
      home: CameraScreen(cameras: cameras),
    );
  }
}

CameraScreen

The layout of this screen is very simple. At the top we will show a real-time camera preview and at the bottom there will be three buttons (swap camera, capture and display Gallery).

Create a stateful widget CameraScreen.

We will create four variables,

We must set selectedCamera = 0, starting with the rear camera. If the device has more than one camera, we can switch to it by changing this index.

Now let's create a method to initialize the selected camera.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-idkp5rxh-1625531278588)( https://ducafecat.tech/2021/07/06/translation/build-a-camera-app-flutter-in-app-camera/2021-07-06-08-07-43.png )]

In this method, we will pass the camera index to initialize. Using the camera list, we will load the specific camera and resolution selection.

Using this method, we will initialize the rear camera in initState.

Don't forget to throw away the camera controller.

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dxwd3err-1625531278590)( https://ducafecat.tech/2021/07/06/translation/build-a-camera-app-flutter-in-app-camera/2021-07-06-08-08-11.png )]

  • Now let's build the UI.

To display CameraPreview, we will use the following code.

FutureBuilder<void>(
  future: _initializeControllerFuture,
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      // If the Future is complete, display the preview.
      return CameraPreview(_controller);
    } else {
      // Otherwise, display a loading indicator.
      return const Center(child: CircularProgressIndicator());
    }
  },
),

Well, now we're going to display three buttons in a row.

Switch / camera button

The first is the switch camera icon button. Click this button and the camera should switch between front and rear.

To do this, we will use the same initializeCamera method, but this time the cameraIndex will be dynamic. cameraIndex the rear camera is 0 and the front camera is 1 (if there is a front camera).

After clicking, we will check whether the device has multiple cameras. If not, we will display a snapbar with a message.

IconButton(
  onPressed: () {
    if (widget.cameras.length > 1) {
      setState(() {
        selectedCamera = selectedCamera == 0 ? 1 : 0;//Switch camera
        initializeCamera(selectedCamera);
      });
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('No secondary camera found'),
        duration: const Duration(seconds: 2),
      ));
    }
  },
  icon: Icon(Icons.switch_camera_rounded, color: Colors.white),
),

Snap button

To display the capture button, I used a simple white circle with a radius of 60. After clicking, we will take a photo using the camera controller and add it to the captureImages array.

GestureDetector(
  onTap: () async {
    await _initializeControllerFuture; //To make sure camera is initialized
    var xFile = await _controller.takePicture();
    setState(() {
      capturedImages.add(File(xFile.path));
    });
  },
  child: Container(
    height: 60,
    width: 60,
    decoration: BoxDecoration(
      shape: BoxShape.circle,
      color: Colors.white,
    ),
  ),
),

Show Gallery button

This button is very simple. We will display the last picture taken from the capturedmages array. When clicked, it will navigate to GalleryScreen.

GestureDetector(
  onTap: () {
    if (capturedImages.isEmpty) return; //Return if no image
      Navigator.push(context,
        MaterialPageRoute(
          builder: (context) => GalleryScreen(
            images: capturedImages.reversed.toList())));
  },
  child: Container(
    height: 60,
    width: 60,
    decoration: BoxDecoration(
      border: Border.all(color: Colors.white),
      image: capturedImages.isNotEmpty
      ? DecorationImage(image: FileImage(capturedImages.last), fit: BoxFit.cover)
      : null,
    ),
  ),
),

As you can see, GalleryScreen accepts a list of captured images, so we can display them in gridview. Let's finish this section to see how the application works.

GalleryScreen

This is a very direct screen. Get a list of images and display them in the GridView.

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

class GalleryScreen extends StatelessWidget {
  final List<File> images;
  const GalleryScreen({Key? key, required this.images}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Gallery'),
      ),
      body: GridView.count(
        crossAxisCount: 3,
        mainAxisSpacing: 2,
        crossAxisSpacing: 2,
        children: images
            .map((image) => Image.file(image, fit: BoxFit.cover))
            .toList(),
      ),
    );
  }
}

Final Product

After building the application, this is the final result.

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zjt1qqu4-1625531278590)( https://ducafecat.tech/2021/07/06/translation/build-a-camera-app-flutter-in-app-camera/2021-07-06-08-10-39.png )]

The camera package can also capture video. You can use startVideoRecording, pauseVideoRecording and stopVideoRecording methods to capture video https://pub.dev/packages/Camera .

This is the Github link of this project. I hope it will help you.

https://github.com/jagrut-18/flutter_camera_app.git

That's it. I hope you like it.

© Cat brother

https://ducafecat.tech/

https://github.com/ducafecat

Previous period

Open Source

GetX Quick Start

https://github.com/ducafecat/getx_quick_start

News client

https://github.com/ducafecat/flutter_learn_news

Translation of strapi manual

https://getstrapi.cn

Wechat discussion group ducafecat

Series collection

translation

https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/

Open source project

https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/

Basics of Dart programming language

https://space.bilibili.com/404904528/channel/detail?cid=111585

Introduction to Flutter zero Foundation

https://space.bilibili.com/404904528/channel/detail?cid=123470

Flutter actual combat news client from scratch

https://space.bilibili.com/404904528/channel/detail?cid=106755

Fluent component development

https://space.bilibili.com/404904528/channel/detail?cid=144262

Flutter Bloc

https://space.bilibili.com/404904528/channel/detail?cid=177519

Flutter Getx4

https://space.bilibili.com/404904528/channel/detail?cid=177514

Docker Yapi

https://space.bilibili.com/404904528/channel/detail?cid=130578