Flutter video player tutorial: How to play videos in Flutter application

In today’s digital age, multimedia content is a crucial aspect of app development. If you’re building a Flutter application and want to incorporate video playback seamlessly, the video_player package is your go-to solution. In this tutorial, we’ll walk through the process of integrating and playing videos in your Flutter app, making your user experience more dynamic and engaging. By the end of this tutorial, you’ll have the skills to elevate your app’s engagement and user satisfaction through the incorporation of immersive video elements. Let’s dive into the world of Flutter video player integration and bring your app to life!

flutter video player example

Supported platforms:

This package supports below platforms.

  • Android (SDK version 16+)
  • IOS (version 11.0 +)
  • macOS (version 10.14 +)
  • Web

Configuration:

You need to make below platform wise configuration.

Android

If you are using network-based videos, ensure that the following permission is present in your Android Manifest file, located in <project root>/android/app/src/main/AndroidManifest.xml:

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

IOS

If you want to access videos using http URL instead of https, you will need to add the appropriate NSAppTransportSecurity permissions to your app’s Info.plist file. This file is located in <project root>/ios/Runner/Info.plist.

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

Check Apple’s documentation to determine the right combination of entries for your use case and supported iOS versions.

macOS

If you are using network-based videos, you will need to add the com.apple.security.network.client entitlement.

Web

The Web platform does not suppport dart:io, so avoid using the VideoPlayerController.file constructor for the plugin. Using the constructor attempts to create a VideoPlayerController.file that will throw an UnimplementedError.

Different web browsers may have different video-playback capabilities (supported formats, autoplay). Check package:video_player_web for more web-specific information. The web implementation of video_player package.

The VideoPlayerOptions.mixWithOthers option can’t be implemented in web, at least at the moment. If you use this option in web, it will be silently ignored.

Install the video_player Package:

First, add video_player as a dependency in your pubspec.yaml file. Ensure to replace latest_version with the actual version.

dependencies:
  flutter:
    sdk: flutter
  video_player: ^latest_version

Run flutter pub get command to download & install the package:

Import the Package:

import the video_player package in your Dart file.

import 'package:video_player/video_player.dart';

Create a VideoPlayerController

Initialize a VideoPlayerController to control the video playback. You can provide the video file URL or asset path.

late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.networkUrl(Uri.parse(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4'))
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });
  }

Note:- VideoPlayerController.network method is deprecated. Instead of this method, use VideoPlayerController.networkUrl method. There is slight change in parameter type.

Display the Video Player Widget

Once the controller is initialized, use the VideoPlayer widget to display the video.

Center(
      child: _controller.value.isInitialized
          ? AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: VideoPlayer(_controller),
            )
          : CircularProgressIndicator(),
    )

Here, we are using VideoPlayer widget to play a video. This widget accepts VideoPlayerController as a parameter. It is mandatory parameter.

In the above code, we are checking whether the video has been loaded and is ready to play or not. In order to check this we are using isInitialized property on VideoPlayerController (i.e:- _controller.value.isInitialized). If the video is loaded, we have wrapped VideoPlayer widget inside AspectRatio widget to show video with proper aspect ratio. Otherwise we are showing circular progress indicator.

Play and Pause Controls

Add play and pause controls to allow users to interact with the video.

ElevatedButton(
                            onPressed: () {
                              setState(() {
                                _controller.value.isPlaying
                                    ? _controller.pause()
                                    : _controller.play();
                              });
                            },
                            child: Icon(
                              _controller.value.isPlaying
                                  ? Icons.pause
                                  : Icons.play_arrow,
                            ))

Use play() method to play the video and pause() method to pause the video. Use isPlaying property to check if video is already playing or not. These methods & property are available on VideoPlayerController class.

Other Controls

Along with above methods & properties, VideoPlayerController class comes with below methods & properties.

position : It is a property. It returns current playing position of a video.

seekTo : This method sets the video’s current timestamp to be at a moment. The next time the video is played, it will resume from the given moment. If the moment is outside of the video’s full range, it will be automatically and silently clamped. This method accepts position as a parameter which is of type Duration class.

setLooping : This method sets whether or not the video should loop after playing once. It accepts boolean value as parameter. Default value is false.

setVolume : This method sets the audio volume of a video. The method parameter is of type double. It accept value between between 0.0 (silent) and 1.0 (full volume) on a linear scale. Default value is 1.0.

setPlaybackSpeed : This method sets the playback speed of video. It accepts speed value in double. For example, when given a value of 2.0, your video will play at 2x the regular playback speed and so on. The speed indicate a speed value with different platforms accepting different ranges for speed values. The speed must be greater than 0.

These methods will make your video player app more feature rich.

Dispose of the Controller

To avoid memory leaks, ensure to dispose the VideoPlayerController object when the widget is disposed.

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

The complete source code is available here.

Conclusion

This Flutter video player tutorial has provided a comprehensive guide on incorporating video playback functionality into your Flutter application using the video_player package.This enhancement will undoubtedly elevate the user experience, making the app more engaging and dynamic. Feel free to explore additional features offered by the video_player package to further customize the video playback experience in your Flutter app.

Leave a Reply

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

*