Learn to make API Requests with Flutter BLoC!! 🔥 #flutter #blocpattern

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign [Music] [Applause] welcome back to a new video and in this video we are going to cover flutter block State Management with apis so I'll tell you like how how can you implement block State Management in flutter for calling apis for making get request post request put patch and delete request right so I've already published two more videos on block one is regarding flutter block Theory where you will get all the theoretical Concepts what is an event what is a state how block works right and another one is on making a simple e-commerce component the card and favorites component using flutter block right so if you have not watched those two videos please watch it and I'll also like to draw your attention to the fact that I'm already out with one paid course on flutter that is completely in simple Hindi language right and where I'm going to publish more than 10 hours of recorded content and we also take live doubt sessions on Discord right so if you have not enrolled please enroll it and you will get a lifetime subscription to it right and you can see that with there we are also learning Advanced State Management Concepts a provider block everything is covered in that course also and that is in the good part is that it is it's in simple Hindi language because most of you were demanding that I'm not teaching uh in Hindi so there I have published one course which is completely in Hindi language so you can consider it the link is in the description now coming back to the topic of the day that is how can we implement or how can we uh call apis make API requests with block right so for that first of all as you know that in Pub spec.gml I need to add some dependencies so I'm going to add block and flutter block so I'm adding block and flutter block right so Ctrl s and it will be saved now I'm going to use a Json placeholder website so it's a complete free website for you where you can actually get free apis you don't need to code a server you don't need to code apis in node.js Express just python go or spring boot right here you can get all the apis get post put patch delete and you can use it for free obviously like data will not be manipulated in their own server it will be like a demo but we will get free apis and we can demonstrate the apis usage of apis right so I'm going to use this you can also use it it's totally free of cost so the website is jsonplaceholder.typical.com I'll put the link in the description right so what happens in this website is you can see that there is slash post so you I I hope that you already know about how apis work what is an endpoint what is a URL right so in this if we hit the slash post if I click on it you can see that I'm going to get this Json so what is Json Json JavaScript object notation now I'm going to get this complete map complete Json and I need to convert this Json into a dart model so that I can use that Dart model in my flutter app so what is going to happen is I can just write it over here for the better explanation we are going to make a request so first step will be make a request right after I make a request I am going to get some data so I'm here I'm talking about the get request okay get request where I'm going to I'm not going to send any data to the server I'm just expecting some data from the server so I'm going to make a request and I'm going to get some data which is in the format of Json so I've got a Json now I need to convert this Json into a dart model so I need to convert this Json into a dart model and then I can update the UI right so there are a couple of things that are happening in this procedure so if you are talking about block obviously we need to talk about events and states right so what will happen first of all when my app will open I want to fire the API I want to call the API okay so my first event will be uh my first event will be call the call the get request or you can say the make a get get request so make a get request all right and as soon as you are going to get some data so you can say that currently my state is loading right this is the loading State and third will be third step will be to get the data so that means mapping I need to convert that Json into a dart model so mapping so this is my third step fourth will be to emitter state so it will be a meta state and this emitter state is going to update the UI update the UI so I can say that as I'm going to work with events and states and I'm going to listen uh or I'm going to continuously consume my blog so I can say that I can use a block consumer so I can also get a listener and I also get a builder so if you have not watched my flutter Theory video I will recommend you that please watch it because there I've covered all these Concepts what is an event State listener consumers Builders providers everything is covered in that uh 30 40 minutes video right so uh this is a general algorithm that we need to build today that we need to code today so without wasting more time let's start it so first of all this is a simple counter app the general basic application that we get in flutter so I'm going to run main.dot and let's see what we get so let's take it up and I'm going to use HTTP package right you can use Dio package also it's totally up to you I'm currently going to use HTTP package so I'm also going to add HTTP over here right so I'm I'm adding HTTP over here so that I can make HTTP request so in the project folder what should we do is first of all um I'm going to have a features folder so in this features folder I'm going to have only one feature for now that is post right so I'm going to make a API request to post I'm not talking about comments albums photos everything I'm interested in post right right so in this features I'm going to add a post folder so post is my feature you can think of right now in this post I'm going to have a block folder so this block folder is also called uh post block right so if I just show you what we have built inside features we have post feature features is having a block block folder in the post folder I'm going to have a UI so now you can see clearly so post is a feature and inside the post I'm having block and UI right I'm also going to have a repositories folder so repositories are you can think of like intermediate stage between my block and the UI or you can say that it is going to make request so it the repositories are going to talk to the network right so I I'll show you you don't need to worry about like what is happening what is repository what is block I'm going to explain each and everything we are going to end this complete project in this video right so don't worry so inside post only I'm going to have a mappers folder so this mappers is going to take a network model or it is going to take the Json and it is going to return me the dart model right simple it's completely simple right not a big deal okay so now we can uh start coding the home or the home that is the first page that my app is going to load so inside features I'm going to have a home folder also so home folder is going to have just a home page so I'm going to have a home page dot dot right this is clear in the main dot dot I'm going to just clear everything and I like to code everything from scratch so material.dot and I'm going to have a stateful widget not a stateful first of all I need to have a void Main I'm going to have a void main which is going to or let's write make it an async function and it is going to have run app and it will be new my app right this is simple in the my app I'm going to create a stateless widget and it is going to be called as my app right in the return I'm going to have a material app debug Banner will be false and I'm going to have a home now in this home I am going to return home which is not yet built so I'm going to go in my home.homepage.dart I'm going to create a stateful widget I'm going to call it as home so in the main I'm going to import my home right so this is clear I can make it a constant right this is clear this is completely easy right this is not a big deal so now what I can do is I am done with uh creating a simple home page so in the home page that what I'm going to do is I'm going to return a scaffold so over here I'm going to return a scaffold and in the scaffold I'm going to have a app bar an app bar which is going to say title as text which is going to have home or you can say post right so post I can say right you can see post no big deal right so what I what I want to do is first of all uh in the UI in the post UI I want to create a uh post page dot dot and I don't I don't want to have home in my folder in my project I just want to like directly go to post page because as soon as I am going to open the app I wish to fetch post from the API right so UI this UI folder is going to have a post page dot dot and I am going to have a stateful widget which is going to have post page this is also going to have scaffold and simple same thing app bar and I'm going to have a title over here which is going to have text post page right and now what I can do is I can remove home and I can just say post page I don't need home for now post space right now what I want to do is uh now let's talk about some events and some states so if I go in post event or dot now what is going to happen in this I'm going to have a event class post initial fetch event that is initial fetch event means as soon as I'm going to open the app the first event the initial event is going to be fetching the post from the API so initial fetch event it is going to extends a post event right so this is a abstract class right and I'm creating my new class so spelling mistake is there initial fetch event okay so now this is the event that will be fired up now again I'm suggesting you that if if you have not watched my one live lecture on block that was uh creating an e-commerce component in Block I would recommend you that you first watch that because there I'm explaining each and everything in simple term like what is an event why I'm writing this class everything is covered in that video right but anyways uh no issues uh if you have not watched it you can still continue but I'll recommend you that you first watch that right so this is the first event so if I just copy it and the post uh block dot dot now I need to code the logic for this I'm just removing everything and I'm writing on so in this on what is going to happen is uh my event is so what happens in Block I hope that you know it that block is going to take an event so event goes inside the block and block emits a state so this is just the importance of block file nothing else block is going to take an event and emitter State that's it okay so my event currently is post initial achievement so my block has got this event that is post initial fetch event and it is going to run some functions and that function is going to emit a state right so block purpose is over so what is the name of the function I can just copy this I can paste it paste it over here and I can make it small P so this is now my function name I can click on this yellow bulb and I can say create method so method will be created that means an empty function is going to get created right so this is an empty function that I need to now fill up with an API call let me just remove it let me just format it yes so this is a this is a simple function now I need to fill this function with an API call right so let's go over here and if I click on slash post this is my API endpoint right this is a get endpoint I can just copy it or what you can do is you can go back and you can click on see guide and you can see getting a resource uh then creating that post request updating a resource patching a resource deleting so everything is over here right you can just read these guides also okay anyways let's go ahead and over here so this function is going to be an async function right async function now what I can do is I can just go on HTTP flutter and I can see what happens in this http. how to make a get request let's say I don't know right so over here I can just copy this request and I can come over here and I can just paste it right so I can see that I need to import HTTP so I'm going to come over here and import HTTP slash HTTP dot dot and I'm going to import it as http right so now my HTTP client is created you can see where client is created now what I need to do is I'm not making a post request I'm making a get request so this will be get and body will not be there in get request I can remove the body and my URI URI is going to be this URI so now in my flutter course also have complete I have taken this same example the same website and I've quoted in in provider and so now I'm going to publish a video there in Hindi in Block also right so if you are interested in learning provider blog everything in Hindi and how to make API requests everything your like it's a complete 10 hours flutter course everything you can enroll into that course right so now what I'm going to do is I'm going to just replace this uh with my URI of Json placeholder right and no comma over here and I can just wrap this one put a semicolon right so this is my response right this is my response so now what I need to do is I need to just uh first of all remove this thing and remove these three lines also and I'm going to have a catch block over here so catch is going to catch an error and what I need to do is as soon as I get an error I want to just log this error log dot string okay so now I've got this response now what I need to do with the response is I need to convert first of all let's print this response let's see what is there in this response so print response dot body right simple I I'm just making a request request is going to send me a response and I'm and I want to see like what is uh the body of that response what I've got in that response right so let's save it and what I need to do is in the post page or dot I'm going to have a init state the United States also I need to first of all create an instance of this block so I'm going to say final post block post block is equal to post block right so I'm creating a simple instance obviously you can create this instance using dependency injection but I'm not using it for now and I'm creating a simple class instance this is simple op concept right in the init State what I need to do is I need to add that initial fetch event so post initial fetch event right so this means the event will go inside the block and block will see okay I need to see I need to run this function and in this function I need to make an API call and in that API call I need to uh print the response whatever that API call is returning simple so now this is done and now what I can do is I can just uh refresh it and I hope to get the response in my console something is there I need to pause it stop it and then run it again because I added HTTP after running my app so let's run it let's see what we get let's see what we get right let's hope that there is no errors but if there are any error obviously we are going to solve it via software Engineers are who life is going to be solving bugs so let's see what we get okay app is built there is one format exception let's see uh I've not got anything Json placeholder.ipigo.com guide okay okay so uh if I go in post block okay I've I've printed the wrong URL so if I just take the URL from here itself that is slash post till here and I can just replace it and let's see let's refresh format exception invalid Radix 10 number URI dot https uri.parse it will be it will be your eye dot parse and I can just refresh okay you can see this is a complete Json that I showed you over there right so if I just copy this URL over here and I paste it in the URL box you can see this is a complete Json we are getting right so here you will see that there are only three nodes there are not three there are all you can see dot so that means it's it has not printed it but there are all uh we have got all the maps of that post right now what I need to do is I need to convert this into a dart module so first of all I'll just close all the files in the lab I'm going to have features I'm going to have post the post I'm going to have models in the models I'm going to create a post model post data UI model you can say data UI model dot dot right so this is a data because this is containing data and it is a UI model so UI model suppose data UI model and I'm going to say class post data UI model and what will be there in this UI model you can see that one map just pick one map from here control C and paste it over here so you can see user ID is there in the format of end so Final End Final End user ID and final again there is an INT so this ID is for the Post ID so Final End ID then we have title so final string title and then we have body so final string body right so I'm going to uh click over here and generate a Constructor so Constructor is created now I can remove this now you can assume that uh if I'm going to get a list of post data UI model if I get the list of post data UI model I can say that I have got this complete Json this complete list is a list of small small Maps list of jsons small small jsons list of dictionaries you can say if you are python background if you have python background right now this is my Dart model right I need to convert my Json into a dart my Json is a list of maps so if I say that I am going to get a list of Dart models I'm satisfying the condition right so now what I need to do is uh I can just also uh create a Json serialization so this generate Json serialization you can see it is going to create two map from map functions right you can also enable this extension adjacent serialization and you are going to get this code or you what you can do is you can go over here you can just Ctrl a Ctrl C and you can also go on quick type so that's an online tool right quick type open Quick type and just paste the whole Json over here and you can see that I'm going to get from Json to Json functions from here also you can just copy it right this is simple or you can use a vs code extension now I've got a post data UI model now I can go in Block post block dot dot now in the response.body I can see that I'm getting a list of Json list of maps right I need to convert one map into a dart model so what I can say that I can in my try on my client I can have a list of post data UI model and it is going to be called post it is an empty list right I need to do is after I'm getting a response I'm going to run a for Loop so for and I equal to 0 I less than response dot body Dot length I plus plus and for every map for every response map I'm going to convert that map into a model dot model and then I'm going to append this post list right so I can say that my post data model post is equal to post data model from map post data UI model sorry not like this post data UI model Dot from map it is going to be a response dot body at I right now what this is saying is string can't be okay so I need to Typecast it as or what I can do is response dot bodyresponse dot data there is something which actually converts into a map what I can say is I can just convert into Json D code so I can say that response.body at I as map as string Dynamic I think it should work I think it should work and after this for loop I can append post dot add my post this should give me something but let's see or now what I need to do is I need to create a state so I can see that class post fetching successful post fetching successful State extends a post state and this state is going to return me final list of post data UI model post data UI model post generator Constructor right and now I can emit the state from the block so I can after this drive in this try block I can say emit state post perfect so this is something that I've got now I'm also going to um print this posts so that we can see that are we getting this list in the console so if we are getting that means there is no error let's see string is not a subtitle map right so what we should be doing is first of all I need to convert this into a list a list that is going to be called as result and this result is going to contain Json decode so I'm just converting my Json into a list of Maps while list of maps because if you will see over here I am getting a list of maps not maps of maps so list of maps so Json D code will be resource or response dot body now I can this is a list right I've got a list of maps now I can say that this will be result dot length right result dot length and it will be result at I result that I post dot add a post and I'm going to return my post and if I just print my post and I just refresh it I just refresh it yes now I can get all my posts you can see instead of posted IUI model instead of posted IUI model now I need to convert or I just need to render this UI so what I'll do is I'll go inside my uipostpage.dart and I'm going to have this container I'm going to wrap this container with a block consumer right and this block consumer this block will be post lock this will be Post State and the block is going to be my post block listener is going to have something we will see it later the Builder is going to have some switch statements so switch case and this will be on type run time of my state now I'm going to get multiple States from my block right now on which state I want to build on which state I want to build right so I want to have two states so I'm going to go in States file I'm going to have one more abstract class date which is going to be for listeners and one post state is going to be for the builders right so post action State extends a post date it is going to extend a Post-It because ultimately we can't return any other state from this block other than Post State right and and this is correct this is correct right I want to listen when my current state is action state so current is post action State and I want to build when my current state is not post action State Post action State correct right and in this I want to first of all uh build when I get post fetching successful state so on post fetching successful State I am going to store this state in a variable so success state is equal to State as a post fetching successful state so this state will be treated as post-successful state and the success state is going to have nothing but my post so you will say over here so you can see my post touching successful is having my post list of posted IUI model now I need to obviously return a listview.builder so container return sorry not return it will be child list view dot Builder this list view dot Builder will have item count as my success state DOT post success state where is the success State okay okay just cut this and remove this break and return it over here right so this success state dot post dot length and my item Builder will have context command X it is going to return a container container container with child which child column children children will have some text text will be post at index post at index dot title so this is this is not post this is Success state DOT post state DOT post at index dot title right if I just save it you are go okay there is one error yeah we have not handled the default state so default state is going to just return a constant size box nothing else right save it you can see titles are there now I need to handle across access alignment dot start right cross excellent dot start so this is now now I need to add some padding and margin adding constant Edge insets dot all 16. and margin will be constant Edge insets dot all 16. right and I need to give it some color so I can give it some color as colors dot gray dot shade 200 see these are all my posts now I can return one more text with the body also and this can be my body correct so these are all the posts that are getting fetched from the internet from the API now if I just refresh you will see there is slight widescreen Gap that's the time when my API is getting loaded so I need to go in my state and I also need to create one loading state so class post fetching loading state it is going to extend Post State because this is a build state and I need to also have one error state so if my API fails what I need to do I need to show one scaffold message or I need to show one alert dialog that is your homework you need to do it error state right or you can also show one four or four page the error the page not found page right so these are the two states now I need to emit this state when my API is getting called so over here at the top itself going to emit my loading state and if some error occurs then I'm going to emit my error state so post fetching error state perfect now in the post page what I'm going to do is in the in the Builder in the case I need to add one more case which is about post loading state and this loading state is going to just return a center child circular progress indicator and it can be constant save it now if you refresh you will see there was instead of white screen there was there there is a circular progress indicator that is coming but that's for very last time because our API is returning as the response very fastly right right so that's not a thing to worry about now what we have learned is we have created a block which fetches the API result and turns it into the flutter UI now I'll teach you how to create a repository so repository is a file or the code that actually uh calls the API right so we need to remove this API calls from the Block because block should only have the business logic not the network logic so this repository is going to have a file called post repo dot dot it is going to be a class post repo and it is going to have a static function it can be non-static then you have to create an instance of the class but I'm just making it static I am calling it as future because it is going to return my future list of post data UI model data UI model fetch post async function right async function and now I can bring the logic the network logic from here to here I also need to import my http and in the HTTP I can just post paste it over here I am having a try block and I also need to have a catch block uh the sketch is going to have some error and I need to log this error if some error occurs this is fine perfect now what we need to do is Json decode we can just import and correct this is correct and at the end instead of printing I need to return my post and the catch for now I can just return an empty list right so this is all correct this is all correct right and I can just go in the block and over here I can say that my list of post data UI model post data UI model post is equal to a weight post repository dot fetch post perfect perfect this can go away this catch can also go away for now yes this is all correct now now if I just um refresh you can see nothing is going to change why because we have just put the network logic in the repository nothing we have changed right now what we need to do is we need to uh I'm going to create one more API call and then we can wrap up the API callback before posting a post that means adding a new post right so I'm going to create an event this is going to be called class post add event right and extends post event rest all the API calls are going to remain same you can actually uh consider it as your homework that will be put request patch request delete request right now for this request I'm going to just hard code the data which I'm going to send to the API in reality what you have to do is you have to create a form and in that form you will be writing title body and then you will be pushing that data to the API right for now just first save your Simplicity I'm just going to hard code that data right how to do it let me show you I have created an event I need to create a function respective function for that event this is correct create a method now in this method in the so this is again a network logic so I'm going to just copy this function and paste it over here and this is not going to return me this this is this is just going to return my Boolean value whether the request was successful or not right and this is going to be add post correct and this is not going to be there API request you can check it from here just go over here and you can see these are the guides and creating a resource is having the same API call endpoint is going to remain same method will be post so what we need to do over here get will become post and this will have my body so let's have body so body will have you can see body is having it have title body and user ID so I'm going to have title so here I am hard coding the data akshit is a flutter teacher let's say right and in the body I'm going to have some data akshit makes good block videos so if you agree with this please drop the like and please uh subscribe to this channel this really motivates me a lot to make more content and if you want more block videos do let me know in the comment section that you want more Blog videos otherwise you can also join my flutter Hindi course where I'm teaching provider blog share preferences everything in Hindi simple Hindi language so you can also consider that link in link is in the description right so now we have user ID so user ID was in int so we can add int or sorry three or let's say any random number I'm just hard coding it right now this for Loop will go away result will go away and if this is successful so I can say that if my response dot status code so can somebody tell me what are the status codes for successful it is obviously greater than equal to 200 and less than 300 and then response dot status code is less than 300 I think it 300 is also including I'm not sure so I'm not including it for now right and I can return true okay and if something happens wrong I can return false so this is the post request and else also I can return false perfect so now I need to call this API request from the block from this thing and I'm going to say uh Boolean success is equal to a weight so I need to bring async also I need to bring a sink also repository dot add post correct and if this is success and you do something if this is if something went wrong so I get uh Boolean as false I need to do something so obviously I need to emit some states so I can say that I am in States file I can say that post Edition success date extends a post State now I want to be an action State because if I just make your post date then my API then my whole screen is going to rebuild and it will be white screen so I want to make it an action State and in this action state in the listener I can say that if this state occurs then I want to emit a I want to show a alert dialogue that hey your post is successful so for this you can actually check out my eCommerce Block video there I have coded very deeply these listeners at the states right so I'll recommend you that if post this is for Success State now obviously one state will be for an error state post Edition error state right this will come in here and let's copy it else it will come over here error state we are done now how to make a how to make this call I am going over here and I'm going to make a floating action button Floating Action button is going to have in the on press it is going to say post block dot add post Edition event post add event right and this is also going to have a child with a add icon I like an icon start add perfect now if I just refresh it and also if I get success or what I need to do is I also want to print my Boolean value print success whether it is true or false if we get true that means API was successful let's refresh and if I click on plus okay there is something wrong let's see it's called without a registered event handler okay okay it says that I have create I'm calling an event but my event is not handled post add event is not handled okay post add event is actually handled so this is not a mistake though post add event is actually handled so if I just refresh again click on plus okay so now we are not getting the adder we are getting another type end is not a sub type of string so this must be in some Repository so we are having only one integer that is this user ID user ID is actually an integer but it is asking me for enter a string I guess the documentation is outdated now let's uh refresh it and refresh it if I click on Plus yes now I get to that means my API was successful this means that uh now what we have learned we have learned to make a get request fetch the post we have learned to make a post request sending the data to the server and we have learned to make a repository file what is the significance of repository file because our block is now much more cleaner it's not dealing with any network logic it's only dealing with the business logic now what is your homework your homework is to first of all like this video have a comment like add a comment on this video subscribe to this Channel and then you need to make put request patch request and delete request push the code on GitHub add me as reviewer my GitHub link is the description and I will review your code right so till Nash content keep coding keep innovating and thanks a lot
Info
Channel: Akshit Madan
Views: 40,328
Rating: undefined out of 5
Keywords: #developer, #flutter, #appdevelopers, #ios, #android, #google, #apple, #data, #datascience, #collegestudents, #engineering, blockchain, freelancer, college, students, internship, web3, solidity, python
Id: ltLJ1AB-eww
Channel Id: undefined
Length: 39min 52sec (2392 seconds)
Published: Wed May 31 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.