Flutter Video Player | video_player Example

Flutter Video Player | video_player Example

This article covers the Flutter Video Player Widget using the video_player plugin. It is very useful to play a native-like Video in the application itself. Both network, as well as local videos, can be played seamlessly.

We will take a look at all the properties of the video_player plugin in dart/flutter and use it to create a video player.

Before jumping on to that, take a look at how to use Stateful Widget as well as Scaffold Widget layouts. Once done, also read about Futures and why we need them in Flutter. We will be making use of all these components in our application.

video_player plugin – Pre-requisites

Before using the VideoPlayer class in Flutter. We will have to take some pre-requisites for IOS and Android Application.

For Android

Make sure, that the minimum SDK is set to 21. You can modify this through the Build Gradle inside the android>app folder.

Once done, make sure that the AndroidManifest.xml file has the Internet permission added. (i.e) add the following line in the Androidmanifest.xml file.

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

Make sure the following lines are added to the info.plist file. This will help in giving permission to use the Internet to render the videos if required. Add the below lines to <project root>/ios/Runner/Info.plist

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

Adding the dependency

Once the above pre-requisites are done. Time to add the dependency to the pubspec.yaml file. Add the following lines to the dependency section and use get packages to sync the project.

dependencies: video_player: ^0.10.1+3

Video_Player plugin – Basics

Video_Player plugin provides the support to play both the network as well as local videos on the device. It creates a simple API for the videos to be called. In this application, we will look at how the Video_Player plugin uses the Controller object and how to create the Future<> Builder to play the video on loading.

As always, we will start off by using the Scaffold Widget as the parent body widget. The idea is to play the video but also provide Button controls to play and pause the video.

In order to call the video player object from any place, we need a controller to hold that. It is possible by using the VideoPlayerController class. We will look at how all of that is pieced together in the below section.

Do not forget to read the last section for a clearer explanation of what the code does. Since we do not have a lot of things going on, I have directly put the code for use below.

Creating the Application

 

import 'dart:async';

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

void main() => runApp(VideoPlayerApp());

class VideoPlayerApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Player Demo',
      home: VideoPlayerScreen(),
    );
  }
}

class VideoPlayerScreen extends StatefulWidget {
  VideoPlayerScreen({Key key}) : super(key: key);

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

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  VideoPlayerController _controller;
  Future<void> _initializeVideoPlayerFuture;

  @override
  void initState() {
    _controller = VideoPlayerController.network(
      'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
    );

    // Initielize the controller and store the Future for later use.
    _initializeVideoPlayerFuture = _controller.initialize();

    // Use the controller to loop the video.
    _controller.setLooping(true);
    super.initState();
  }

  @override
  void dispose() {
    // Ensure disposing of the VideoPlayerController to free up resources.
    _controller.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),
      backgroundColor: Colors.orangeAccent,
      appBar: AppBar(
        title: Text('Bee Video'),
        backgroundColor: Colors.black87,
      ),
      // Use a FutureBuilder to display a loading spinner while waiting for the
      // VideoPlayerController to finish initializing.
      body: Stack(
        children: <Widget>[
          Center(child:FutureBuilder(
            future: _initializeVideoPlayerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                // If the VideoPlayerController has finished initialization, use
                // the data it provides to limit the aspect ratio of the video.
                return AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  // Use the VideoPlayer widget to display the video.
                  child: VideoPlayer(_controller),
                );
              } else {
                // If the VideoPlayerController is still initializing, show a
                // loading spinner.
                return Center(child: CircularProgressIndicator());
              }
            },
          )),
          Center(
              child:
              ButtonTheme(
                  height: 100.0,
                  minWidth: 200.0,
                  child: RaisedButton(
                    padding: EdgeInsets.all(60.0),
                    color: Colors.transparent,
                    textColor: Colors.white,
                    onPressed: () {
                      // Wrap the play or pause in a call to `setState`. This ensures the
                      // correct icon is shown.
                      setState(() {
                        // If the video is playing, pause it.
                        if (_controller.value.isPlaying) {
                          _controller.pause();
                        } else {
                          // If the video is paused, play it.
                          _controller.play();
                        }
                      });
                    },
                    child: Icon(
                      _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                      size: 120.0,
                    ),
                  ))
          )
        ],
      ),
    );
  }
}

This creates the application which looks like,

Flutter Video Plugin
Flutter Video Plugin
Flutter Video Plugin
Flutter Video Plugin

Code Explanation

We have written a lot of lines of code above. We will take a look at what the individual module does and why it is required.

initState

InitState module takes care of initializing the 2 important objects that we need. The controller object to control the video(Any actions like play, pause, fast forward, etc) and the Future<> object to hold the VideoPlayer object to wait till the video starts.

Scaffold

Once the two simple objects for the Flutter Video Player are created. Time to get all the pieces together. Starting with the FutureBuilder widget. It provides a clean interface to wait until an object is available. Meaning, a video from the network might take some time to load. The FutureBuilder takes care of waiting till this object is loaded while providing some other Widgets in the meantime(In this example, it is a simple CircularProgressIndicator). Once the object arrives, the video starts playing.

ButtonTheme

The final piece to the puzzle. It creates one button which is going to control the video state. If the button is pressed, the video will stop playing and on clicking the button again, the video will start playing. This is possible by using the _controller object we saw above.

Using _controller.play() or _controller.pause() this is possible.

Similar way, we can create any number of buttons we need, and use the controller object to play around with the Video’s controls.

Video Player Plugin- Conclusion

Using the Video Player Plugin in Flutter is straight forward. Note: There is a pending issue with Video not playing for IOS simulator. In that case, try to run the app in a real-time device.

Drop in any comments below.

“Learn and Be Curious”

Leave a Comment

Your email address will not be published. Required fields are marked *