flutter video player widget plugin

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will build a Flutter application by making use of Flutter Video Player Widget Plugin to display/play videos in our Flutter App with example.

Introduction to video player flutter widget

Flutter Video Player is a plugin developed by the flutter team for Android, iOS, and Web development so that developers can easily make use of this video pkg widget library in integrating playing videos in their apps.

Important Note: As mentioned in official site that, This plugin is still under development, some latest API version of this video player library may give some kind of bugs.

let’s Start with installation of this widget in our flutter project

Flutter Video Player Widget Tutorial

Video Tutorial

Step 1: Create a new Project

offCourse you need to create a new Flutter Project or Open any existing project, all depends to you.

In my case, I m making use of Android Studio to Develop Flutter application.

Files > New > New Flutter Project

Step 2: Installation of Video Player Plugin

Adding dependencies

Open pubspec.yaml file and add the below video_player flutter dependencies version

dependencies:
  video_player: ^2.1.1 // version might change so check the official site

Import the video_player.dart

Once you have added the video player plugin, now you will be able to use video pkg by importing the library file where required.

import 'package:video_player/video_player.dart';

In my case i have imported video_player.dart file in main.dart file

Step 3: Adding Internet permission in android and iOS

Android

Please make sure to add the following Internet permission in your Android project manifest file.

Naviget to : <project root>/android/app/src/main/AndroidManifest.xml:

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

The Flutter project template adds it, so it may already be there.

iOS

For iOS devices Navigate to <project root>/ios/Runner/Info.plist:

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

and just add the above keys.

Step 4 : Network configuration android version 9 ( Optional )

This Step is optional, do this only if you are facing any problem in loading the video.

Create a directory names ” xml ” under the following path:

<project root>/android/app/src/main/res

In this xml folder you need to create a new xml resource file  

xml(dir) > (Right click) New > xml Resource file > and name the file as networkconfig.xml

Then, add the following Network Config code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">commondatastorage.googleapis.com</domain>  //here replace with you localhost server or your domain name
    </domain-config>
</network-security-config>

Here is example of the directory structure:

network config android

Step 5 : The Complete Code for Flutter Video Player

main.dart 

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {

  VideoPlayerController controller; // used to controller videos
  Future<void> futureController;  // network takes time to load video, so to control future video data

  @override
  void initState() {

    //url to load network
    controller = VideoPlayerController.network("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4");
    futureController = controller.initialize();

    controller.setLooping(true);  // this will keep video looping active, means video will keep on playing
    controller.setVolume(25.0);  // default  volume to initially play the video 
    super.initState();

  }

  @override
  void dispose() {
    controller.dispose();  // when app is been closed destroyed the controller
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar(
        title: Text("Flutter Video Player Example"),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: FutureBuilder(
              future: futureController,
              builder: (context,snapshot){
                // if video to ready to play, else show a progress bar to the user
                if(snapshot.connectionState == ConnectionState.done)
                  {
                    return AspectRatio(
                      aspectRatio: controller.value.aspectRatio,
                      child: VideoPlayer(controller)
                    );
                  }else{
                    return Center(child: CircularProgressIndicator(),);
                }
                
              },
            ),
          ),
          //button to play/pause the video
          RaisedButton(
            color: Colors.transparent,
            child: Icon(
              controller.value.isPlaying? Icons.pause : Icons.play_arrow
            ),
            onPressed: (){
              setState(() {
                if(controller.value.isPlaying)
                  {
                    controller.pause();
                  }
                else
                  {
                    controller.play();
                  }
              });
            },
          )
        ],
      )
    );
  }
}