How to create Camera Preview in flutter

In this Google Flutter code snippet example, we are going to learn how to create a camera preview with Flutter.

You can copy and adopt this source code example to your flutter project easily without issues.

In your pubspec.yaml file, add this

camera: any

Create a new file named camera_preview.dart (or call it any name of your choice). And the code below.

import 'dart:async';

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

class CamPreview extends StatefulWidget {
  _CamPreviewState createState() => _CamPreviewState();

class _CamPreviewState extends State<CamPreview> {
  CameraController _controller;
  Future<void> _initCamFuture;

  void initState() {

  _initApp() async {
    final cameras = await availableCameras();
    final firstCam = cameras.first;

    _controller = CameraController(

    _initCamFuture = _controller.initialize();

  void dispose() {

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Camera Preview")),
      body: FutureBuilder<void>(
        future: _initCamFuture,
        builder: (context, snapshot) {
          //if (snapshot.connectionState == ConnectionState.done) {
            return CameraPreview(_controller);
          /* } else {
            return Center(
              child: CircularProgressIndicator(),
          } */

In your main.dart file (main entry point of the app), add this:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch:,
      home: new CamPreview(),

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment