How to Integrate YouTube Video Player in a Flutter Application

How to Integrate YouTube Video Player in a Flutter Application

Introduction

YouTube is one of the world’s popular social media platforms for hosting and sharing videos. You can find a great list of music, movies, tutorials, documentaries and interviews in any domain there. Many enterprises, corporations and freelancers create and share videos on their various channels to enhance communication and provide a better user experience on the various services they offer. YouTube has become an indispensable social asset in the daily lives of many entrepreneurs and organizations.

Objectives

This guide will cover the necessary steps you need to follow to integrate YouTube into your Flutter application. In a nutshell, you will build a simple application like in the demo below.

Youtube Flutter Player Demo in Drive

Common Use Cases Where You Should Add YouTube Integration in Your Mobile App

Before diving into the main subject, it’s important to know when and where to integrate YouTube into your application. Some of the common use cases are:

Integrating Video Tutorials

One of the easiest ways to enhance user experience and improve engagement is by adding video tutorials from your channel or various subject matters that can interest your audience.

If you own a course or food application or a simple informational application, integrating YouTube can help users easily and efficiently get access to video content from your various channels that align with their interests.

Integrating in Movies Application

Adding movie trials or reviews via YouTube in your movie application allows users to get a preview of a specific movie and helps them decide whether to watch it or not. You can equally add behind-the-scene footage to spice up the app and encourage users to spend longer time on your application hence improving user engagement.

Informational oriented application

Informational-centered applications that provide articles, blog posts, and news about a variety of subjects can be enhanced by adding video-related content to improve user comprehension further.

Monetization

Implementing a YouTube player with ad support in your application provides a revenue stream for your application. For example, if you have a food recipe application, you can generate revenue by displaying YouTube videos with ads before, during or after the video.

Live Stream Events

You can embed YouTube live stream video using the YouTube LIVE API into your application easily for real-time interaction with your audience, product launch or Q&A sessions which can improve the kind of services you offer and user engagement.

Product Demonstrations

For educational applications or e-commerce applications, you can integrate YouTube videos to showcase the product features, the benefits of using it and real-life usage to the users in-app.

Travel

A mobile app that includes travel guides or travel-related content with embedded YouTube videos showcasing popular destinations, attractions, or travel tips.

For example, users can easily visualize popular spots instantly rather than navigating through a list of selected images.

Fitness and Music

In fitness applications, you can incorporate YouTube videos that demonstrate and guide users on how to perform certain movements.

Keep in mind that while integrating these YouTube features into your mobile application, it’s important to always ensure compliance with YouTube’s terms of service.

Integrating YouTube in a Flutter Application

In this section, we will work you through on how to integrate Youtube player in your Flutter application.

Prerequisites

Creating a Flutter Application

Open your Android Studio editor and create a new Flutter project or open your terminal and run the following command to get started with a Flutter project.

flutter create example_project_youtube

example_project_youtube is the name of the project, and you can replace it with any name you want. Once the project is complete, choose an emulator or connect your phone and run the following command to launch it.

flutter run

Adding YouTube Package

To add the youTube_player_flutter package, open another terminal and run the following command:

flutter pub add youtube_player_flutter

youtube_player_flutter plugin for playing or streaming inline YouTube videos using the official iFrame player API. This plugin supports both Android and iOS.

This will add the youtube_player_flutter package in the dependencies section of your pubspec.yaml located at the root of your project.

dependencies:
  flutter:
    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  youtube_player_flutter: ^8.1.2

Now create two dart files in which one will contain the video JSON data model and the last will be the YouTube player page.

We also have the main.dart file which look like this:

import 'package:flutter/material.dart';
import 'package:flutter_app_youtube/screens/YoutubeScreen.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.red),
        useMaterial3: true,
      ),
      home: const YouTubeScreen(),
    );
  }
}

Create a lib/model/VideoModel.dart and add the following code:

import 'dart:convert';
class VideoModel {
  int? id;
  String? name;
  String? url;
  VideoModel(this.id, this.name, this.url);
  VideoModel.fromJson(Map<String, dynamic> json) {
    id = json["id"];
    name = json['name'].toString();
    url = json['url'];
  }
}

Create YouTubeVideoScreen.dart

import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class YouTubeScreen extends StatefulWidget {
  const YouTubeScreen({Key? key}) : super(key: key);
  @override
  _YouTubeScreenState createState() => _YouTubeScreenState();
}
class _YouTubeScreenState extends State<YouTubeScreen> {
  String? videoId;
  @override
  void initState() {
    super.initState();
    videoId = 't31fj-0t3Dw';
  }
  @override
  Widget build(BuildContext context) {
    return YoutubePlayer(
      controller: YoutubePlayerController(
        initialVideoId: videoId!,
        flags: const YoutubePlayerFlags(
          autoPlay: true, 
          mute: false
        )
      )
    );
  }
}

A Youtube video url is generally in the form:

https://www.youtube.com/watch?v='Your video id here'

The v in the url contains the id of your video. So put this id in the videoId varaible and test your application

Incorporating Features and Customizing YouTube Player

Show Video Progression Indicator

By default, the showVideoProgressIndicator is set to true, you can set it to false if you don’t want to see the video progression indicator.

showVideoProgressIndicator: false

Progress Indicator Color

Use the progressIndicatorColor attribute to change the color of the video progress indicator. For example, below we have changed the color to green:

progressIndicatorColor: Colors.green

Setting FullScreen Mode

To support Full screen you need to wrap the player in the YoutubePlayerBuilder:

YoutubePlayerBuilder(
  player: YoutubePlayer(
    controller: _controller,
  ),
  builder: (context, player){
    return Column(
      children: [
        player,
      ]
    );
  }
),

Adding Players Control

YoutubePlayerFlags allows you to define player flags. In the example below, we set the autoplay to false, disabled the audio by setting mute to true, enabled caption, and hide controls, looped the video and disabled video HD mode.

YoutubePlayerFlags(
  autoPlay: false,
  mute: false,
  enableCaption: true,
  loop: true,
  forceHD: false,
  hideControls: true
)

If you want to know more you can check the YoutublePlayerFlags Class and equally learn how to customize other features.

What’s Next

Conclusion

In this guide, we have learned how to integrate a YouTube video player into a Flutter application. By following the step-by-step guide and code examples provided, you can enhance your app’s functionality and user experience by seamlessly incorporating YouTube videos. Remember to handle error cases gracefully and consider implementing additional features like Playback Speed and playlist integration to further enrich your app.

Flutter YouTube Player increases the productivity of your applicant by providing visual and dynamic content that makes your application both informative and engaging. You can add a YouTube video player in any application as you can see through the use cases provided earlier.

With the power of Flutter and YouTube integration, the possibilities are endless.

Happy coding!
Full GitHub Code of Tutorial.

Resources

https://pub.dev/packages/youtube_player_flutter

https://www.linkedin.com/pulse/why-considering-video-integration-mobile-apps-profitable-abbas/

https://developers.google.com/youtube/v3/code_samples/code_snippets