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

Ducafecat WeChat group

B station…

The original…




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


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.

  onTap: () async {
    await _initializeControllerFuture; //To make sure camera is initialized
    var xFile = await _controller.takePicture();
    setState(() {
  child: Container(
    height: 60,
    width: 60,
    decoration: BoxDecoration(
      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.

  onTap: () {
    if (capturedImages.isEmpty) return; //Return if no image
          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.


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: / /

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

That’s it. I hope you like it.

The elder brother of the © cat

The issue of

Open source

GetX Quick Start…

News Client…

Strapi manual translation

WeChat discussion group Ducafecat

A series of collections

The translation…

The open source project…

DART programming language basics…

Flutter Zero Basics Beginners…

Flutter combat news client from scratch…

Flutter component development…

Flutter Bloc…

Flutter Getx4…

Docker Yapi…