How to Show Live Image Preview from Camera in Flutter App

In this example, we are going to show you the way to display a live image preview feed from Camera as a widget in your Flutter App. Additionally, you will learn to capture the image and display captured image in your app. See the example below:

First of all, you need to add camera plugin to your project by adding the following lines in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  camera: ^0.9.4+11

Now for Android, set the minimum SDK version to 21 at android/app/build.gradle

minSdkVersion 21

Now, for iOS, add the following lines in ios/Runner/Info.plist

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

Now, in your script part, import the camera plugin:

import 'package:camera/camera.dart';

Now, declare the required variables in your widget class:

List<CameraDescription>? cameras; //list out the camera available
CameraController? controller; //controller for camera
XFile? image; //for caputred image

Initialize the  camera controllers:

cameras = await availableCameras();
if(cameras != null){
  controller = CameraController(cameras![0], ResolutionPreset.max);
              //cameras[0] = first camera, change to 1 to another camera
              
  controller!.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
  });
}else{
  print("NO any camera found");
}

Now, you can display the preview from Camera inside your app using CameraPreview() widget:

CameraPreview(controller!)

You can capture the image using the following code:

image = await controller!.takePicture();

You can display captured image inside your app using the following widget:

Image.file(File(image!.path))

import 'dart:io';

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



Future<void> main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}


class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  List<CameraDescription>? cameras; //list out the camera available
  CameraController? controller; //controller for camera
  XFile? image; //for caputred image

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

  loadCamera() async {
      cameras = await availableCameras();
      if(cameras != null){
        controller = CameraController(cameras![0], ResolutionPreset.max);
                    //cameras[0] = first camera, change to 1 to another camera
                    
        controller!.initialize().then((_) {
            if (!mounted) {
              return;
            }
            setState(() {});
        });
      }else{
        print("NO any camera found");
      }
  }

  @override
  Widget build(BuildContext context) {
    
    return  Scaffold(
          appBar: AppBar( 
              title: Text("Live Camera Preview"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            child: Column(
              children:[
                  Container(
                      height:300,
                      width:400,
                      child: controller == null?
                          Center(child:Text("Loading Camera...")):
                                !controller!.value.isInitialized?
                                  Center(
                                    child: CircularProgressIndicator(),
                                  ):
                                  CameraPreview(controller!)
                  ),



                  Container( //show captured image
                     padding: EdgeInsets.all(30),
                     child: image == null?
                           Text("No image captured"):
                           Image.file(File(image!.path), height: 300,), 
                           //display captured image
                  )
              ]
            )
          ),

          floatingActionButton: FloatingActionButton(
            onPressed: () async{
                try {
                  if(controller != null){ //check if contrller is not null
                      if(controller!.value.isInitialized){ //check if controller is initialized
                          image = await controller!.takePicture(); //capture image
                          setState(() {
                             //update UI
                          });
                      }
                  }
                } catch (e) {
                     print(e); //show error
                }
            },
            child: Icon(Icons.camera),
          ),
           
       );
  }
}

In this way, you can display live image preview from camera inside you app.

No any Comments on this Article


Please Wait...