Building a YouTube Playlist Viewer in Flutter: A Step-by-Step Guide

Snehal Singh 👩‍💻
5 min readAug 23, 2024

--

Flutter is a versatile framework that allows developers to create beautiful and high-performance mobile, web, and desktop applications from a single codebase. In this blog, we’ll walk through the process of building a YouTube playlist viewer in Flutter, where users can browse playlists, view videos in a playlist, and play videos using the YouTube Player.

Prerequisites

Before we begin, ensure that you have the following:

  • Flutter SDK: Make sure Flutter is installed and configured on your machine.
  • YouTube Data API Key: You’ll need to enable the YouTube Data API in the Google Developer Console and obtain an API key.
  • Channel ID: ID of the YouTube channel you want to show the playlist for.

Overview of the Application

Our application will consist of three main screens:

  1. Playlist Screen: Displays a list of playlists from a specific YouTube channel.
  2. Playlist Videos Screen: Shows all the videos within a selected playlist.
  3. Video Player Screen: Plays the selected video using the youtube_player_flutter package.

Let’s dive into each screen and build our application step by step.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:
flutter:
sdk: flutter
youtube_player_flutter: ^9.0.3

Step 2: Import

import 'package:youtube_player_flutter/youtube_player_flutter.dart';

Step 3: Install the dependencies

Run the below command in the root directory of your app to install dependency.

flutter pub get

Step 4: Let’s Start Building

1. Creating the Playlist Screen

The first step is to create the PlaylistScreen that fetches and displays playlists from a YouTube channel.

Fetching Playlists from YouTube

To fetch playlists, we’ll use the YouTube Data API. Below is the code to fetch playlists and display them in a grid.

Future<List<Playlist>> fetchPlaylists() async {
final String url =
'https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=$channelId&key=$apiKey&maxResults=50';

final response = await http.get(Uri.parse(url));

if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
final List<dynamic> playlists = data['items'];
List<Playlist> playlistList = playlists.map((item) {
final snippet = item['snippet'];
return Playlist(
id: item['id'],
title: snippet['title'],
thumbnailUrl: snippet['thumbnails']['default']
['url'], // Use 'medium' or 'high' for better resolution
);
}).toList();
return playlistList;
} else {
throw Exception('Failed to load playlists');
}
}
Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // Number of items per row
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
childAspectRatio:
3 / 2, // Adjust to make the cards look better
),
itemCount: playlists.length,
itemBuilder: (context, index) {
return PlaylistCard(
playlist: playlists[index],
onTap: () {
// Navigate to Playlist Video Screen
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PlaylistVideoScreen(
playlistId: playlists[index].id,
),
),
);
},
);

What We Did:

  • API Call: We fetched the playlists from a specific channel using the YouTube Data API.
  • PlaylistCard Widget: Each playlist is displayed using a custom PlaylistCard widget, showing the playlist thumbnail and title.
  • Navigation: On tapping a playlist card, we navigate to the PlaylistVideoScreen to view the videos in the playlist.

2. Creating the Playlist Video Screen

The next step is to create the PlaylistVideoScreen, where we'll display all the videos from the selected playlist.

Fetching Videos from the Playlist

We’ll use the YouTube Data API again to fetch the videos using the playlistId.

Future<List<Video>> fetchVideos(String playlistId) async {
final String url =
'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${playlistId}&key=$apiKey&maxResults=50';

final response = await http.get(Uri.parse(url));

if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
final List<dynamic> videosJson = data['items'];
List<Video> fetchedVideos =
videosJson.map((json) => Video.fromJson(json)).toList();
return fetchedVideos;
} else {
throw Exception('Failed to load playlists');
}
}
ListView.builder(
itemCount: videos.length,
itemBuilder: (context, index) {
return ListTile(
leading: Image.network(videos[index].thumbnailUrl),
title: Text(
videos[index].title,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
onTap: () {
// Navigate to Video Player Screen
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
videoId: videos[index].id,
),
),
);
},
);

What We Did:

  • API Call: We fetched the videos from the selected playlist.
  • ListView: The videos are displayed in a ListView, with each item showing the video thumbnail and title.
  • Navigation: When a video is tapped, we navigate to the VideoPlayerScreen to play the video.

3. Creating the Video Player Screen

Finally, we’ll create the VideoPlayerScreen to play the selected video using the youtube_player_flutter package.

Integrating YouTube Player

To play the video, we’ll use the youtube_player_flutter package. Here's the code:

@override
void initState() {
super.initState();
_controller = YoutubePlayerController(
initialVideoId: widget.videoId,
flags: const YoutubePlayerFlags(
mute: false,
autoPlay: true,
),
);
_controller.toggleFullScreenMode();
}
YoutubePlayerBuilder(
player: YoutubePlayer(
controller: _controller,
showVideoProgressIndicator: true,
onReady: () {
print('Player is ready.');
},
onEnded: (YoutubeMetaData metaData) {
Navigator.pop(context);
},
),
builder: (context, player) {
return Column(
children: [
player,
// Add more widgets below if needed
],
);
},
)

What We Did:

  • YouTube Player Integration: We initialized the YoutubePlayerController with the selected video ID and configured it to autoplay the video.
  • Full-Screen Mode: The video automatically enters full-screen mode when the screen is opened.
  • Lifecycle Management: The player controller is properly disposed of to prevent memory leaks.

Conclusion

In this tutorial, we built a simple yet powerful YouTube playlist viewer in Flutter. We’ve covered how to fetch playlists and videos using the YouTube Data API, display them in a user-friendly interface, and play videos using the YouTube Player.

This application can be further enhanced with features like search, filtering, or even downloading videos for offline viewing. Flutter’s flexibility and the vast ecosystem of packages make it a great choice for developing multimedia-rich applications.

Feel free to experiment with the code, customize the UI, and add more features to make it your own!

Full Souce Code

Here is the source code that you can clone and use for your application.
GitHub Link: YouTube Playlist App & E-Learning App also consists of one module.

Please Follow đź’™ and clap đź‘Ź, if you find the article useful. And get notified of my upcoming articles.

Follow me on Twitter: @imsnehalsingh and Github: Snehal Singh to hear about my projects.

--

--

Snehal Singh 👩‍💻
Snehal Singh 👩‍💻

Written by Snehal Singh 👩‍💻

SDE - 2 at DhiWise | Flutter Developer đź’™ | Women Techmakers Ambassador | Technical Writer & Instructor at Udemy

No responses yet