How to use Front Camera in Flutter

In this Google Flutter code snippet example, we are going to learn How to use front camera in flutter

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

add this code to your pubspec.yaml file

 camera: ^0.5.2+1

Create a front_cam.dart file (use any name of your choice) and add this code:

 import 'dart:async';

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

class FrontCamera extends StatefulWidget {
  @override
  _FrontCameraState createState() => _FrontCameraState();
}

class _FrontCameraState extends State<FrontCamera> {
  CameraController _controller;
  Future<void> _initCamFuture;

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

  _initApp() async {
    final cameras = await availableCameras();
    //slect another camera here
    final frontCam = cameras[1];

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

    _initCamFuture = _controller.initialize();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Front Camera ")),
      body: FutureBuilder<void>(
        future: _initCamFuture,
        builder: (context, snapshot) {
          
            return CameraPreview(_controller);
          
        },
      ),
    );
  }
}

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

import 'package:inducesmile/front_cam.dart.dart';

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

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.