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 {
  @override
  _CamPreviewState createState() => _CamPreviewState();
}

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

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

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

    _controller = CameraController(
      firstCam,
      ResolutionPreset.medium,
    );

    _initCamFuture = _controller.initialize();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  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 {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

50% Discounts On Projects

Do you have a custom project with a clear requirements, we are currently giving a 50% discount on all projects.

We will work with you to ensure we deliver what you need.

If you have questions or want to chat with us, you can reach us on Skype (henry.tochi)

Languages and technologies we use - Java, Kotlin, Laravel, Vue, React, Flutter, Swift and more.