How to record video using Camera in Flutter

In this Google Flutter code snippet example, we are going to learn How to record video using camera in flutter

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

Add this code to your pubspec.yaml file

 camera: ^0.5.2+1

Create a record_video.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';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

class CamVideo extends StatefulWidget {
  @override
  _CamVideoState createState() => _CamVideoState();
}

class _CamVideoState extends State<CamVideo> {
  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("Record Video")),
      body: FutureBuilder<void>(
        future: _initCamFuture,
        builder: (context, snapshot) {
          
            return CameraPreview(_controller);
          
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.videocam),
        onPressed: () async {
          try {
            await _initCamFuture;

            final path = join(
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );

            await _controller.startVideoRecording(path);
          } catch (e) {
            print(e);
          }
        },
      ),
    );
  }
}

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

import 'package:inducesmile/record_video.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 CamVideo(),
    );
  }
}

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