Integrating YouTube videos into a Flutter app can significantly enhance user engagement. Whether you’re developing an educational app or creating a platform for content sharing, displaying YouTube videos directly within your app is a useful feature. The youtube_player_flutter package simplifies this task, making it easy to embed and control YouTube videos with minimal setup.
In this comprehensive guide, we’ll cover how to use the youtube_player_flutter package in your Flutter app, including setup, customization, and handling common use cases.
What is youtube_player_flutter
and Why Should You Use It?
The youtube_player_flutter
package provides a powerful and easy-to-use YouTube video player widget for Flutter. It supports various player controls like play, pause, seek, and full-screen mode, allowing seamless integration of YouTube videos in any Flutter app. Using this package helps you avoid the hassle of embedding YouTube’s iframe API or dealing with web views.
Key features include:
- Full YouTube Player control with play, pause, and seek functionality.
- Customizable UI to match your app’s design.
- Support for both portrait and landscape video playback.
Now, let’s walk through how to set it up and use it.
Setting Up youtube_player_flutter
Step 1: Add Dependencies
To get the dependency click here or add the youtube_player_flutter
package to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
youtube_player_flutter: ^9.1.1
Run flutter pub get
to install the package.
Step 2: Import the Package
Next, import the package into your Dart file where you want to use the YouTube player:
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
How to Initialize and Play YouTube Videos
To play a YouTube video, you need to create a YouTube player controller and pass the video’s ID. The video ID is the unique identifier found in YouTube URLs. For example, in the URL https://youtu.be/zEY9n4YMiQs?si=BkoacO6I2MCylduB
, the video ID is zEY9n4YMiQs
.
Example: Simple YouTube Player
import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class YouTubePlayerExample extends StatefulWidget {
@override
_YouTubePlayerExampleState createState() => _YouTubePlayerExampleState();
}
class _YouTubePlayerExampleState extends State<YouTubePlayerExample> {
late YoutubePlayerController _controller;
@override
void initState() {
super.initState();
_controller = YoutubePlayerController(
initialVideoId: 'zEY9n4YMiQs', // Replace with your video ID
flags: YoutubePlayerFlags(
autoPlay: false,
mute: false,
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('YouTube Player'),
),
body: YoutubePlayer(
controller: _controller,
showVideoProgressIndicator: true,
onReady: () {
print('Player is ready.');
},
onEnded: (metaData) {
print('Video has ended');
},
),
);
}
}
Explanation:
- YoutubePlayerController: This controller manages the playback of the video.
- initialVideoId: The YouTube video ID you want to play.
- YoutubePlayerFlags: These flags control player behavior, such as autoplay or mute.
- YoutubePlayer(): This widget displays the YouTube player in the app.
- showVideoProgressIndicator: Shows a progress bar below the video.
With this setup, you can now play YouTube videos within your Flutter app!
Customizing the YouTube Player
The youtube_player_flutter
package allows you to customize the player’s behavior and appearance to match your app’s style.
Example: Full-Screen Mode and Custom Controls
To enable full-screen playback and customize player controls, you can modify the YoutubePlayerFlags
and add buttons for controlling playback.
class YouTubePlayerWithControls extends StatefulWidget {
@override
_YouTubePlayerWithControlsState createState() => _YouTubePlayerWithControlsState();
}
class _YouTubePlayerWithControlsState extends State<YouTubePlayerWithControls> {
late YoutubePlayerController _controller;
@override
void initState() {
super.initState();
_controller = YoutubePlayerController(
initialVideoId: 'zEY9n4YMiQs', // Replace with your video ID
flags: YoutubePlayerFlags(
autoPlay: false,
mute: false,
enableCaption: true,
isLive: false,
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Custom YouTube Player'),
),
body: Column(
children: [
YoutubePlayer(
controller: _controller,
showVideoProgressIndicator: true,
progressIndicatorColor: Colors.red,
onReady: () {
print('Player is ready.');
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.play_arrow),
onPressed: () {
_controller.play();
},
),
IconButton(
icon: Icon(Icons.pause),
onPressed: () {
_controller.pause();
},
),
IconButton(
icon: Icon(Icons.stop),
onPressed: () {
_controller.seekTo(Duration.zero);
_controller.pause();
},
),
IconButton(
icon: Icon(Icons.fullscreen),
onPressed: () {
_controller.toggleFullScreenMode();
},
),
],
),
],
),
);
}
}
Explanation:
- Custom Controls: Added play, pause, stop, and fullscreen buttons to control video playback.
- YoutubePlayerFlags(enableCaption: true): Enables captions on the video, if available.
- toggleFullScreenMode(): Toggles between fullscreen and normal mode.
This example demonstrates how you can easily control playback and enable fullscreen mode with custom buttons.
Handling Player Events
You may want to handle events such as when a video starts playing, pauses, or ends. The youtube_player_flutter
package provides built-in event handlers for these.
Example: Handling Video Events
YoutubePlayer(
controller: _controller,
onReady: () {
print('Player is ready.');
},
onEnded: (YoutubeMetaData metaData) {
print('Video ended: ${metaData.title}');
},
)
Available Events:
- onReady: Triggered when the player is ready for interaction.
- onEnded: Triggered when a video has finished playing.
Using these event listeners, you can add additional functionality like loading another video or showing an alert when the current video finishes.
Playing YouTube Playlists
You can also play YouTube playlists with youtube_player_flutter. Here’s how to do it:
_controller = YoutubePlayerController(
initialVideoId: 'PLFgquLnL59akA2PflFpeQG9L01VFg90wS', // Playlist ID
flags: YoutubePlayerFlags(
autoPlay: true,
loop: true,
),
);
In this case, you just need to pass the playlist ID instead of the video ID, and the player will handle playlist playback for you.
Saving and Loading Player State
In many cases, you may want to save the video’s playback state and resume it when the user returns to the app. You can handle this by saving the player’s position using onStateChange
and restoring it later.
Example: Saving and Restoring Playback Position
Duration _lastPosition = Duration.zero;
YoutubePlayer(
controller: _controller,
onReady: () {
_controller.seekTo(_lastPosition); // Restore playback position
},
onEnded: (metaData) {
setState(() {
_lastPosition = _controller.value.position; // Save position
});
},
)
In this example, the player will resume from where the user left off when the app reopens or the video is played again.
Conclusion
The youtube_player_flutter package is an excellent tool for embedding YouTube videos into your Flutter app with ease. Whether you need basic playback functionality or advanced custom controls, this package covers all your needs. With full-screen support, customizable player controls, and event handling, you can create a seamless YouTube viewing experience for your users.
Happy Coding…!!!
Leave a Reply