Be sure to retweet brother for more Flutter posts at ~~~~

Ducafecat WeChat group

B stationhttps://space.bilibili.com/40…

The original

https://medium.com/geekcultur…

code

https://github.com/jagrut-18/…

reference

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

The body of the

In many applications, we require the user to upload an image by clicking on it. To do this, we can use the device’s default camera app, but what if we need to integrate an in-app camera? Well, it’s also possible to Flutter. Group has developed a https://pub.dev/packages/camera called camera, it can let us do it.

Establishing the project

First, install the Camera package into the project by adding the following line to the pubspec.yaml file.

Camera: ^ 0.8.1 + 3
  • IOS Settings

This plugin requires iOS 10.0 or later. Add the following line to the info.plist file to set the contents.

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

Change the minimum version of the Android SDK to 21(or higher) in the Android/app/build.gradle file.

minSdkVersion 21

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

We will create two screens in our application.

1.CameraScreen ー This screen will display camera output and take pictures

2.GalleryScreen ー This screen will display captured images in a grid view.

Loading camera

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

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

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

So, the camera will go through like this

After all this, this is what main.dart looks like.

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 the screen is simple. At the top we will show a live camera preview and at the bottom there will be three buttons (swap camera, capture and show gallery).

Create a stateful widget, cameraScreen.

We’re going to 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.

In this method, we pass the camera index to initialize. Using the list of cameras passed through, we will load the specific camera with a resolution of choice.

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

Don’t forget to drop the camera controller.

  • 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()); }}),

Okay, now we’re going to display three buttons in a row.

Switch/camera button

The first is the button to switch the camera icon on and off. Click this button and the camera should switch back and forth.

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

Upon clicking, we will check if the device has multiple cameras, and if not, we will display a snackbar 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), ),

Capture button

To display the capture button, I used a simple white circle with a radius of 60. Once clicked, we’ll use the camera controller to take a photo 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,
    ),
  ),
),

Display gallery button

This button is very simple, we will display the last image taken from the CapturedMages array, and when clicked, it will navigate to GalleyScreen.

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 the GridView. Let’s finish this section to see the application in action.

GalleryScreen

It’s a very straightforward screen. Gets a list of images and displays 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.

Camera bag can also capture video, you can use startVideoRecording, pauseVideoRecording and stopVideoRecording method to capture the HTTP: / / https://pub.dev/packages/Camera.

Here’s the GitHub link to this project, I hope it’s helpful.

https://github.com/jagrut-18/…

That’s it. I hope you like it.


The elder brother of the © cat

https://ducafecat.tech/

https://github.com/ducafecat

The issue of

Open source

GetX Quick Start

https://github.com/ducafecat/…

News Client

https://github.com/ducafecat/…

Strapi manual translation

https://getstrapi.cn

WeChat discussion group Ducafecat

A series of collections

The translation

https://ducafecat.tech/catego…

The open source project

https://ducafecat.tech/catego…

DART programming language basics

https://space.bilibili.com/40…

Flutter Zero Basics Beginners

https://space.bilibili.com/40…

Flutter combat news client from scratch

https://space.bilibili.com/40…

Flutter component development

https://space.bilibili.com/40…

Flutter Bloc

https://space.bilibili.com/40…

Flutter Getx4

https://space.bilibili.com/40…

Docker Yapi

https://space.bilibili.com/40…