Video player in Flutter – Flutter video_player plugin

In this post, you will learn to create a video player app using a flutter plugin called video_player. This plugin makes it very simple to create a video player.

From the official doc:

A Flutter plugin for iOS, Android and Web for playing back video on a Widget surface.

How to use video_player in flutter?

(Android only)

Let’s see the steps to use the Flutter video player plugin.

The first step after creating a new Flutter project is to add the video_player dependency to the project’s pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  video_player: ^2.4.7

Add the internet permission to the AndroidManifest.xml file if you want to play a video from the network.

Provide the following permission in the AndroidManifest.xml file. You will find AndroidManifest.xml file under Android/app/src/main/AndroidManifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ...>

    </application>

    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

To load the video from assets, create an assets folder at the root level of the project, and inside this folder create a video subfolder, then add the video you want to display inside the video subfolder. The file path should then be specified as follows in the assets section of pubspec.yaml:

flutter:
  assets:
         - assets/videos/

Import the video_player package. I am importing it into the main.dart file.

import 'package:video_player/video_player.dart';

Now, get the instance of VideoPlayerController and initialize it. See the code below.

@override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.asset(
        'assets/videos/waves.mp4');
    _controller.initialize().then((_) {
      //Calling the setState() method when the video initialization is complete
      // will update the UI. This makes sure that the first frame is shown even
      // before pressing the play button.
        setState(() {});
      });
  }

When the video initialization is complete, the setState() method will trigger the UI to rebuild. You call the setState() method to ensure that the first frame of the video is shown even before pressing the play button.

Here, I load the video from the assets. If you want to play a video from the network, use the code below:

 @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(
      'URL_to_video',
    );
    _controller. Initialize().then((_) {
      //Calling the setState() method when the video initialization is complete
      // will update the UI. This makes sure that the first frame is shown even
      // before pressing the play button.
        setState(() {});
      });
  }

To display the video that the VideoPlayerController has initialised, the video player plugin offers the VideoPlayer widget. You wrap the VideoPlayer widget in an AspectRatio widget. But why? Because the VideoPlayer widget occupies the maximum amount of space by default. To ensure that the video has correct proportions, enclose the VideoPlayer widget in an AspectRatio widget.

_controller.value.isInitialized
                  ? AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    )
                  : SizedBox(height: 200,),

If the initialization is complete, display the video, otherwise, display the SizedBox widget (can also use Container widget here.).

Now let’s see the full code.

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

void main() => runApp(const VideoApp());

class VideoApp extends StatefulWidget {
  const VideoApp({Key? key}) : super(key: key);

  @override
  _VideoAppState createState() => _VideoAppState();
}

class _VideoAppState extends State<VideoApp> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.asset(
        'assets/videos/waves.mp4');
    _controller.initialize().then((_) {
      //Calling the setState() method when the video initialization is complete
      // will update the UI. This makes sure that the first frame is shown even
      // before pressing the play button.
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Demo',
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _controller.value.isInitialized
                  ? AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    )
                  : SizedBox(height: 200,),
                  VideoProgressIndicator(_controller, allowScrubbing: true),
                  ElevatedButton(
                      onPressed: () {
                       setState(() {
                        _controller.value.isPlaying
                        ? _controller.pause()
                        : _controller.play();
                        });
                      },
                      child: Icon(
                        _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                     ),
               ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    //Dispose the VideoPlayerController to free up resources.
    _controller. Dispose();
  }
}




 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: