Flutter YouTube API and Video Player Tutorial | Apps From Scratch

hey everyone welcome back to apps from scratch today we'll learn how to interact with the YouTube API paginate data and play videos in our app we

display a user's profile image named sub count and a list of their most recent videos when we scroll down to the bottom of the list we request the next batch of videos from the YouTube API and update

our list of videos we can play any video by tapping on her cell which brings us to a new screen and place the video if you're new here I'd appreciate it if you like and subscribe before we get started

I'm excited to let you know that I have just launched a new course on udemy that focuses on building beautiful UI in flutter step by step if you enjoy my apps from scratch series on my youtube

channel you'll love this course throughout this course you'll build the UI of a food delivery app budget app and social media app all while improving your skills

along the way I really put a lot of thought into this new course and I'd love for you to check it out I'll leave a link with the coupon code down in the description below and with that let's

get started the first thing that we're going to do is jump into our pub spec Toyama file and add the dependencies HTTP and YouTube player flutter the HTTP plugin allows us to send a request to

our API to get data while the YouTube player flutter plugin allows us to play youtube videos using the official YouTube iframe player API the only setup we have to do is for the YouTube player

flutter plugin on iOS devices where we add the key IO dot flutter embedded underscore views underscore preview to our info.plist file and set the value to yes Android devices on the other hand do

not require any setup in order to interact with the YouTube data API we need an API key to authenticate our HTTP requests let's go to consult

developers.google.com/maps and click new project let's name our project YouTube API and then select create once our project sets itself up we go to go to API overview

and then select enable api's and services here we can search for YouTube and then select YouTube data API v3 click enable

and then click rate credentials here let's select YouTube data API v3 select either iOS or Android and then select public data now we can click what credentials do I need and here's our API

key we can select this to copy and then also click restore key here we can scroll down and select restrict key select api's and then check YouTube data API

and it's safe back in our ID a new folder called utilities and a new file called keister inside key start you will create an API

key constant and set it equal to the API key we just copied before pushing our project to github it's very important to add our keys that dart file to our projects docket ignore file because we

don't want to expose our API key we can do this by right clicking the keys at dart file selecting copy relative path and then pasting it into our get ignore when we add our project to github our

keys that dart file will not be included now we're going to make a new folder under the Lib directory called models and inside we will create channel model dot org

channel model will consist of eight different properties and has a factory channel dot from map method that returns an instance of channel when we pass in our decoder JSON

data now we receive from the API if we compare the parsing in our from map function to the JSON data we can clearly see how we retrieve values from the data for example in order to get the profile

picture URL we go in to snip it then thumbnails default and then URL which returns the URL as a string for the upload playlist ID we go into content details then related playlists and then

uploads which returns our playlist ID as a string to make video model dark our video model will have four different properties and just like our channel

model it also has a factory from map method here we pass on our decoder JSON data where we grab the values for our video ID video title thumbnail and channel title if we want to get the

video ID we go into the resource ID then video ID which returns the ID of our video as a string back in channel model dart remember to import video model dart so our videos list does not have an

error next we're going to create a services folder and an API service start file of our file make sure you have all these imports

we'll have two private variables base URL and next page token base URL is the first part of the URL we request data from next page token stores the string value used to identify the next batch of

videos when paginating our data in order to keep track of our next page token throughout the lifetime of our app we're going to turn our API service class into a singleton by defining a method called

API service underscore instantiate and then creating a static final instance variable equal to API service underscore instantiate if you want to explore the YouTube API

before we write our functions to retrieve data you can go to developers.google.com/plus you tube / v3 slash Doc's which is very well documented we're going to be fetching

data from the channels and playlist items endpoints the first function we're going to write is fetch channel which takes a channel ID and returns a future channel as it's

asynchronous we create a URI which consists of the base URL we defined above and specifies the channel endpoint we want to hit our parameter specify the data we wanted to receive from the API

like the snippet content details and statistics it contains the ID of the channel we want to view and our API key to authenticate our get request the contents of our headers variable

ensures that the get requests returns a JSON object get the response from I get requests we await HTTP GET and passing our URI and headers then we check if our response

has a status code of 200 which means that it successfully retrieved data we decode the body of our response and store the first value of the items list energy son which contains the channel

information in a map after we use our factory method to convert the map to a channel object we fetch the first batch of the channels uploaded videos with the next function will write called fetch

videos from playlist assign the videos to the channels videos property and return the channel in the event our response fails and returns a status code that is not 200 we decode the responses

body and throw the error message the fetch videos from playlist function takes the playlist ID which is the uploaded videos playlist ID just like our fetch channel function we define

parameters a URI and headers for our parameters we only request data in snippet for the post ID we set the max number of videos returned in each request state and set the page token to

the current next page token in our app in our URI we hit the playlist items endpoint once we receive a response from our get request we check if the request is

successful and then decode the body of a response into a JSON object we store the next page token and if data next page token does not exist or is null then we set the next page token to an empty

string we store the list of JSON video objects located in data items in the variable videos JSON then we iterate over videos JSON and convert each JSON snippet to a video object which we add

to our videos list and return and again in the event our response fails and returns a status code that is not equal to 200 we decode the responses body and throw the error message now we're ready

to create our home screen which will display our data let's make our screens folder and file home screen dart screened art we create our stateful widget home screen and have a return a

scaffold back in main dart let's remove all the boilerplate code remove the debug banner change the primary color of our app to colors red and set our home to home screen which we have to import

in homescreen dart will have two instance variables the first is channel and the second one is is loading which we will use for imagination let's add an inert state function and

call the asynchronous function in its channel unit channel fetches a channel based on a channel ID and sets the state of our homescreens channel variable you can find my channel ID by going to

my channel and copying the string of characters after channeled for slush our build method will have a scaffold that contains an app bar with a title text YouTube channel for the body of our

scaffold we will have a ListView builder with an item count equal to one plus the number of videos in the channels video list we add one because we need an extra item for our channel information so if

the index is equal to zero then we return our function build profile info otherwise we grab the video from Channel videos index minus one and pass it into our build video function underneath init

channel let's write build profile info it will return a container margin padding height and a box shadow the child of the container is a row widget that has a circle avatar that loads the

channels profile picture a sized box with a width of 12 point O and an expanded column widget with two text widgets our channel title and subscriber account text widgets have the property

overflow text-overflow:ellipsis to prevent very long text from going off the screen the build video method takes in a video and returns a container with properties similar to our build profile

info the child of our container is a row widget that displays our videos thumbnail image in title text when you hit save in Hot restart the app you may notice that there is an error that

flashes about channel being null this is because our build method runs briefly before our asynchronous init channel function sets the state of our channel variable we can fix this by checking if

channel is not equal to null in the beginning of our scaffolds body if the channel is not null then we render the ListView builder otherwise we display a centered red circular progress indicator

to red scrolling pagination to our app we wrap our ListView builder in a notification listener scroll notification inside the on notification function we

have an if statement that checks three things the first is if we are not already loading more videos the second is if the number of videos currently in our channels videos list is not equal to

the total number of videos the channel has the third checks if we are at the bottom of our list view using the scroll details from on notification then we call the function load more videos and

return false right above our build method let's create the asynchronous function load more videos we set is loading to true to ensure that we do not fetch more video as multiple times once

we fetch the next batch of videos we combine the current channels video list with the new batch and update our channel's video state with set state to update our apps UI then we set is

loading back to false so the user can load more videos when the bottom of the list is reached now we're going to add video screen dart to our screens folder

they stateful Wojcik called video screen that takes in a final string ID which is the idea of the video we want to view remember to import material dart and the YouTube player flutter package at the

top of the file in our video screen state class we have a controller of type YouTube player controller that we instantiate inside our niche state method we'll set the video player to not

be on mute and autoplay the video when it loads insider build method we have an app bar so we can navigate back to our home screen with the back button the body of our scaffold contains the

YouTube player widget that will display our video for us to watch in homescreen dart we want to navigate to our video screen when we tap on a video container let's wrap our container in our build

video method with a gesture detector and pass the video ID to our video screen by using navigator I'll push in the on top function if we tap a video we are brought to our

video screen and the video Auto place and now we completed our YouTube API and video player app as always remember to leave a like subscribe share this video and star the repository on github don't

forget to check out my new flutter UI udemy course if you want to improve your UI skills and I'll see you in the next one [Music]

» UDEMY: The Complete Flutter UI Masterclass Coupon
https://www.udemy.com/course/the-complete-flutter-ui-masterclass/?couponCode=B5D3C1BA98B898FC6605

» UDEMY: Flutter and SQFLite Coupon
https://www.udemy.com/course/flutter-and-sqflite/?couponCode=749216595DBD298E3599

This tutorial series will teach you how to build awesome user interfaces and complete apps with Flutter and Dart. In this video, we build out a complete app using the YouTube API. We’ll learn how to interact with the YouTube API, paginate data, and play videos!

» Remember to like, subscribe, share this video, and star the repo on Github 🙂
https://www.youtube.com/MarcusNg?sub_confirmation=1

» Resources
Source Code: https://github.com/MarcusNg/flutter_youtube_api
http package: https://pub.dev/packages/http
youtube_player_flutter package: https://pub.dev/packages/youtube_player_flutter
Google Developers Console: https://console.developers.google.com/
YouTube API Documentation: https://developers.google.com/youtube/v3/docs
My Channel ID: UC6Dy0rQ6zDnQuHQ1EeErGUA

» Studying for coding interviews?
https://algoexpert.io/marcus
Use promo code “marcus” for a discount!

» Socials
GitHub: https://github.com/MarcusNg
Twitter: https://twitter.com/MarcusLNg

» My Gear*
LG 29″ UltraWide 21:9 IPS Monitor: https://amzn.to/34mbzYk
Logitech Master MX 2S Wireless Mouse: https://amzn.to/35BZoYy
AirPods 2: https://amzn.to/2MdpJVb
Apple Magic Keyboard: https://amzn.to/2nCXqpu
Blue Yeti USB Microphone: https://amzn.to/32cs6wM
JBL Charge 3 Bluetooth Speaker: https://amzn.to/2IZuxeT

*Affiliate links

» Outro Music
Harmony – Joakim Karud (https://www.youtube.com/channel/UCVBUm9ccjHy0utvlChyrPHA)

#Flutter #FlutterTutorial #AppsFromScratch

    advanced flutter app development app from scratch apps from scratch basic flutter game tutorial beginner flutter card chat ui tutorial dart dart ui firebase fireship first flutter game first mobile game flutter flutter advanced tutorial flutter api tutorial flutter app from scratch flutter apps from scratch flutter beginner app flutter beginner course flutter beginner game flutter beginner tutorial flutter chat flutter chat app flutter chat design flutter chat tutorial flutter chat ui flutter chat ui tutorial flutter data pagination flutter flame flutter for beginners flutter full app flutter game app flutter game dev flutter game development flutter game tutorial flutter games flutter gaming flutter get request flutter mobile game flutter paginate data flutter save highscore flutter save score flutter shared preferences flutter simple api flutter spawn enemies flutter stack flutter travel app flutter travel app tutorial flutter travel design flutter travel ui flutter travel ui tutorial flutter ui flutter ui course flutter ui tutorial flutter ui ux flutter video flutter video player flutter video streaming flutter youtube api flutter youtube clone flutter youtube design flutter youtube tutorial flutter youtube ui game development gamedev how to build a chat app how to build a travel app how to build flutter chat kalle hallden listtile listview mobile mobile development mobile game development one day flutter build one day flutter builds programming travel app tutorial tutorial whatsapp