How to Display Youtube Videos from Youtube API in Flutter

How to Display Youtube Videos from Youtube API in Flutter

Hello everyone, welcome back at porkaone. On this occasion we will learn how to use the YouTube API and display it in Flutter. Are you curious? Come on, follow the tutorial below.


In the previous tutorial, I discussed how to display YouTube videos using static data written in flutter files, this article was written in Indonesian https://www.sahretech.com/2023/06/mudah-membuat-dan-menampilkan-video.html

Just by using static data, the application we create is not dynamic. In our tutorial this time, we will try to use data from the YouTube API. Every time the application is run, the video will be updated according to data from the YouTube API. Please scroll to the bottom of this article to see the final results.

Read Another Article ✨
📰 1. How to Create a Select Dropdown with API in Flutter  read more
📰 2. How to Create a Select Input Dropdown in Flutter  read more
📰 3. How to Make a QR Code Scanner in Flutter ENV read more
📰 4. How to Display Youtube Videos in Flutter  read more


How to Display Youtube Videos from Youtube API in Flutter

1. First, you have to get a YouTube Api key to be able to access data from YouTube Api. Please follow the tutorial on how to get the YouTube API key below https://www.porkaone.com/2023/12/how-to-get-youtube-api-key.html

2. Ok, next create a new flutter project with the name you want. And use the latest version of flutter.

3. Open pubspec.yaml then add the http: and youtube_player_flutter: packages, follow the example as shown in the image below. And don't forget to save the file to download the package.

Youtube API Flutter
Add Package


4. Create a video.dart file in the lib folder. This file is used as a video data model. Follow the script below



class Video { final String id; final String title; final String thumbnail; final String channelTitle; Video({required this.id, required this.title, required this.thumbnail, required this.channelTitle}); factory Video.fromJson(Map<String, dynamic> json) { return Video( id: json['id']['videoId'] ?? '', title: json['snippet']['title'] ?? '', thumbnail: json['snippet']['thumbnails']['high']['url'] ?? '', channelTitle: json['snippet']['channelTitle'] ?? '' ); } }


5. Create the youtube_api_service.dart file in the lib folder. And don't forget to change YOUR_API_KEY in the script below according to your respective api key. Follow the script below



import 'dart:convert'; import 'package:http/http.dart' as http; import 'video.dart'; class YouTubeApiService { Future<List<Video>> getVideos() async { final url = 'https://www.googleapis.com/youtube/v3/search' '?part=snippet' '&maxResults=10' '&q=flutter+tutorial' '&type=video' '&key=YOUR_API_KEY'; final response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { final jsonData = json.decode(response.body); final videoList = jsonData['items'] as List<dynamic>; return videoList.map((item) => Video.fromJson(item)).toList(); } else { throw Exception('Failed to load videos'); } } }

Explanation:

  1. We can use this YoutubeAPIService class for all files that require YouTube data.
  2. getVideos() is a method for retrieving YouTube data. The return is in the form of a list with the Video model
  3. final url we use this url as the endpoint. There are several parameters that you can set. maxResults= is used to display the number of videos. q= is the query or video we want to search for, you can adjust it according to what you want. Here I am looking for a flutter tutorial. type= This parameter is used to choose whether to display videos or channels.
  4. key= fill in the api key that you got from the Google console.

If the settings are correct then the data can be displayed. If the settings are wrong then it will run an error message throw Exception('Failed to load videos'). If an error occurs, please consult in the comments column below.


6. Create a detail.dart file in the lib folder. Follow the script below.



import 'package:flutter/material.dart'; import 'package:youtube_player_flutter/youtube_player_flutter.dart'; import 'video.dart'; import 'youtube_api_service.dart'; class Detail extends StatefulWidget { final String videoId; final String title; Detail({ required this.videoId, required this.title, }); @override State<Detail> createState() => _DetailState(); } class _DetailState extends State<Detail> { late YoutubePlayerController _controller; @override void initState() { super.initState(); _controller = YoutubePlayerController( initialVideoId: YoutubePlayer.convertUrlToId( 'https://www.youtube.com/watch?v=' + widget.videoId)!, flags: const YoutubePlayerFlags( autoPlay: false, mute: false, ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Video Detail'), ), body: ListView( children: [ YoutubePlayer( controller: _controller, showVideoProgressIndicator: true, progressIndicatorColor: Colors.blueAccent, ), Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( width: 35, height: 35, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage( 'https://cdn.pixabay.com/photo/2016/11/18/23/38/child-1837375_640.png', ), ), ), ), const SizedBox( width: 10, ), Expanded( child: Text( widget.title, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w400), maxLines: 2, overflow: TextOverflow.ellipsis, ), ), ], ), const SizedBox( height: 20, ), const Text( 'See Other Videos', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500), ), const SizedBox( height: 15, ), FutureBuilder<List<Video>>( future: YouTubeApiService().getVideos(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } else if (snapshot.hasData) { final videos = snapshot.data!; return ListView.builder( padding: EdgeInsets.zero, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: videos.length, itemBuilder: (context, index) { final video = videos[index]; return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ InkWell( onTap: () => { Navigator.push( context, MaterialPageRoute( builder: (context) => Detail( videoId: video.id, title: video.title, ), ), ) }, child: ListTile( contentPadding: EdgeInsets.zero, leading: Image.network( video.thumbnail, fit: BoxFit.cover, width: 120, ), title: Text( video.title, maxLines: 2, overflow: TextOverflow.ellipsis, ), ), ), const SizedBox( height: 8, ), ], ); }, ); } else if (snapshot.hasError) { return Center( child: Text('Error: ${snapshot.error}'), ); } else { return Center( child: Text('Failed to load videos'), ); } }, ), ], ), ) ], ), ); } }


7. Buat file main.dart di dalam folder lib. Ikuti script di bawah ini.



import 'package:flutter/material.dart'; import 'youtube_api_service.dart'; import 'detail.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'video.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('YouTube Videos'), ), body: FutureBuilder<List<Video>>( future: YouTubeApiService().getVideos(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } else if (snapshot.hasData) { final videos = snapshot.data!; return ListView.builder( itemCount: videos.length, itemBuilder: (context, index) { final video = videos[index]; return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => Detail( videoId: video.id, title: video.title, ), ), ); }, child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Image.network( video.thumbnail, width: double.infinity, height: 160, fit: BoxFit.cover, ), const SizedBox( height: 5, ), Padding( padding: EdgeInsets.all(8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( width: 45, height: 45, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage( 'https://cdn.pixabay.com/photo/2016/11/18/23/38/child-1837375_640.png', ), ), ), ), const SizedBox( width: 10, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( video.title, style: const TextStyle( fontSize: 16, ), maxLines: 2, overflow: TextOverflow.ellipsis, ), SizedBox(height: 5,), Text( 'Channel : '+video.channelTitle, style: const TextStyle( fontSize: 12, ), maxLines: 2, overflow: TextOverflow.ellipsis, ), ], ), ), ], ), ), SizedBox(height: 10,) ], ), ), ); }, ); } else if (snapshot.hasError) { return Center( child: Text('Error: ${snapshot.error}'), ); } else { return Center( child: Text('Failed to load videos'), ); } }, ), ), ); } }


We have done all the steps, it's time to test it. Please run the emulator and if successful, the display will look like the image below.

Cara Menampilkan Video Youtube dari API di Flutter      Cara Menampilkan Video Youtube dari API di Flutter



That's a short tutorial on how to display YouTube videos from YouTube Api in Flutter. Hopefully this short tutorial is useful. If you have any questions, please ask directly in the comments column below. That is all and thank you.

Post a Comment

0 Comments