How to display Youtube videos in Flutter

Flutter Jun 19, 2023

In this post, we will explore how to display YouTube videos in a Flutter application using the youtube_player_flutter package. We will cover the steps involved in setting up the project, installing the package, adding the YoutubePlayer widget, avoiding memory leaks, and customizing the player behavior using YoutubePlayerFlags.

1. Setting up our project

To begin, let us set up our Flutter project and import the necessary dependencies. Adjust the code in the main.dart file with the following:

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'YouTube Player Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('YouTube Player Demo'),
      ),
      body: const Center(),
    );
  }
}

In this code snippet, we set up the basic structure of our Flutter application with MyApp as the root widget and MyHomePage as the home screen. The application includes an AppBar and to start a body with the Center widget, providing a foundation for the integration of the YouTube player functionality.

1.1 Installing the package

Next, we need to install the youtube_player_flutter package. Open your terminal and execute the following command: flutter pub add youtube_player_flutter.

Ensure that the installation is successful by checking if the dependencies in your pubspec.yaml file includes the following:

dependencies:
  flutter:
    sdk: flutter
  youtube_player_flutter: ^8.1.2

The youtube_player_flutter package requires a minimum SDK version of 17, or else it will throw an error. To adjust this in your project, navigate to the following path: $your_project/android/app/build.gradle and open the build.gradle file. Locate the defaultConfig block and update the targetSdkVersion to 17, as shown below:

defaultConfig {
    applicationId "com.example.codeonwards_demo"
    minSdkVersion 17
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

In this code snippet, we replacedminSdkVersion flutter.minSdkVersion with minSdkVersion 17. To make sure that the minimum required version of the Android API is 17.

2. Implementing the Youtube player

To display a Youtube player in our MyHomePage widget we need to make the following changes in the MyHomePage widget, see the code snippet below:

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    YoutubePlayerController controller = YoutubePlayerController(
      initialVideoId: 'PAOAjOR6K_Q',
    );

    return Scaffold(
      appBar: AppBar(
        title: const Text('YouTube Player Demo'),
      ),
      body: Center(
        child: YoutubePlayer(
          controller: controller,
        ),
      ),
    );
  }
}

In this code snippet, we created a YoutubePlayerController instance to control the Youtube player. We passed in the YouTube video ID to load a specific video, the ID can be found after watcht?v=  in the URL of the video https://www.youtube.com/watch?v=PAOAjOR6K_Q. We also added the YoutubePlayer as a child in our Center widget. The YoutubePlayer requires a controller, so we passed in the controller we created.

flutter_displaying_a_youtube_video

2.1 Avoiding Memory Leaks

In order to avoid memory leaks we have to make sure that our controller is properly disposed of. For this, we need to convert our MyHomePage widget into a stateful widget.

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    YoutubePlayerController controller = YoutubePlayerController(
      initialVideoId: 'PAOAjOR6K_Q',
    );

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('YouTube Player Demo'),
      ),
      body: Center(
        child: YoutubePlayer(
          controller: controller,
        ),
      ),
    );
  }
}

In this code snippet, we transformed our MyHomePage widget to extend the StatefulWidget widget. We have created our _MyHomePageState class to make sure that we can override the dispose function. As you can see inside the dispose function we dispose of our controller by calling controller.dispose. The dispose function is called whenever a widget is permanently removed from the widget tree. In our case making sure that the controller is properly disposed of.

2.2 Adding YoutubePlayerFlags

Additionally, you can customize the behavior of the YoutubePlayer by providing flags through the YoutubePlayerController. These flags allow you to control settings such as muting the video, enabling captions, forcing HD quality, and hiding controls.

YoutubePlayerController controller = YoutubePlayerController(
  initialVideoId: 'PAOAjOR6K_Q',
  flags: const YoutubePlayerFlags(
    mute: false,
    autoPlay: true,
    enableCaption: true,
    forceHD: true,
    hideControls: false,
  )
);

This code snippet demonstrates the customizing of the YouTube player by adjusting attributes within the YoutubePlayerFlags class. Below is a comprehensive list of available options and their functionalities for easy reference.

  • autoPlay: Define whether to auto-play the video after initialization. Default: true.
  • captionLanguage: Specifies the default language that the player will use to display captions. Default: 'en'.
  • controlsVisibleAtStart: If set to true, controls will be visible at the start. Default: false.
  • disableDragSeek: Disables seeking video position when dragging horizontally. Default: false.
  • enableCaption: Enabling causes closed captions to be shown by default. Default: true.
  • endAt: Specifies the default endpoint of the video in seconds.
  • forceHD: Forces High Definition video quality when possible. Default: false.
  • hideControls: If set to true, hides the controls. Default: false.
  • hideThumbnail: Hides thumbnail if true. Default: false.
  • isLive: If true, Live Playback controls will be shown instead of the default ones. Default: false.
  • loop: Enabling this causes the player to play the video again and again. Default: false.
  • mute: Mutes the player initially. Default: false.
  • showLiveFullscreenButton: Defines whether to show or hide the fullscreen button in the live player. Default: true.
  • startAt: Specifies the default starting point of the video in seconds. Default: 0.
  • useHybridComposition: Set to true to enable Flutter's Hybrid Composition. Default: true.

3. Conclusion

Integrating YouTube videos into Flutter applications can be achieved easily using the youtube_player_flutter package. To get started, make sure you have set up your project correctly by including the necessary dependencies and adjusting the minimum SDK version if required.

Tags