Flutter Consume Rest API With Best Practices

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys and welcome to coding orbit in this video i will show you how to implement and consume rest api into your flutter application we will parse the data of the api into dart models and then we will display it on the ui now we are not going to use it the easy way just calling an api and returning the result now we will go over the best practices and you will learn how to implement it using best practices in dart and the flutter now before we get started if you haven't subscribed yet make sure to subscribe and turn on your notification bell so you don't miss our content now let's get started all right to get this started i've already created a flutter application inside the main i'm having material app and then home home with this home widget doesn't have anything on the scaffold and text news article with center title now i have already created the design for the widget article widget i'm not gonna go over it we will focus on implementing the api now inbox back to tml i already added also json annotation and http these libraries we will be using and they also added build runner and json's realizable because we will use them throughout the tutorial now let's go to the browser and i've already also created an account in this news api website and let's have a look at the result we will get we will first get status then total result then articles and we'll get the object of source that has id and name and then some attributes for each and we will have uh 38 of these now as you can see the api is has a get request and it has these query parameters which are the api key and country so we will be using them so let's go back to android studio and close this and inside the lib let's first create a new directory and let's call it static and inside it let's create a dart file and let's call it static values and in here we will create a class called static values and then inside that we will create this constructor and then we will create an api url and then we will create the api keys and then we will create the api country all right now let's go to data again and let's create a new directory and let's create a directory called models and inside it let's create a new dart sorry a new dart file and let's call it article underscore model now inside here i will actually paste the model instead of boring view and typing everything and before i do anything let me just show you i will take this and bring this and i will minimize the project now you can see that we have status and total results and articles now inside this model we don't care about all of these we only care about one object inside the articles now we have the source and the source is actually here we have string id and string name and then we have the author the author is here and since the author might be null and some result below the author might be null so i added json key default value unknown in case it's null because i was using it in the design and i have a title and description as you can see title and description and url the url is the article url and then i have url to image which i didn't like its name so i change it to image url and then i add the json key with name url to image and published ad and content now we don't care if the content is null or published that so all of these are not available except for the author and i also added a factory article dot from json and i created these two functions for each of these classes and i added also json serial serializable above them so let's just go back to android studio and expand the project so you could see a little bit better and now we have three errors the first error is this error part and we added for the command that we will run so it will create from json method for us this method and this method as well now before we run that i just want to say create to json to false because we're not going to use 2json in here so i will add it inside here too and to make this work make sure that you have no error in the flutter project except for these three the part and these and these now go to the terminal and type flutter pop run build runner build and hit enter it will work for a little bit of time and then it will generate these methods and you can see that it also generated this file this file hold these methods this is for article source and this is for the whole article and you can see that it immediately added the unknown if it's not all right now our next step is to go back to the lib and create new directory and we will call this directory network now we will create a new file inside that we'll call it query underscore param which is stand for query parameters and here we'll create a class called qp and then we will create a constructor so we can't initialize this class now after it will create static map string string and we will call it api qp now here this method should take required string and it should take the api key and it also should take the country so required string country as well okay and this returns a map which first has a country and inside here we'll provide the country then here we'll provide api key and let me just make sure that i wrote it right the api key so i will copy it from here and paste it here and here i'll provide the api key with sent and just add semicolon here and that's it for this class all right now let me minimize this and let me close the model and close the static so now on we will focus on the network directory now we will create a new dart file and we will call it network underscore service now inside here we'll create a class called network service and this also shouldn't be initialized so we will say const network service dot underscore all right now the first thing we will do we will import http inside here http slash http. and we will call it as http now first we will create headers and headers are also so we'll create static map headers are also string string and we will make this method private so we will call it get headers it doesn't take anything however it returns only for now it will return content type which is application slash json sorry all right now since we want this to be generic and we don't want to limit ourselves for the news api so we will create an nm sorry and we will call it request type and inside here we have get we have what we have post we have many more you can add whatever you want or what you will use in your application now we will create a generic method that holds all the api calls inside our application so we will create static and this is future and we will use http dot response and it might be null so we'll make it also private and we will call it create request now this request since we wanted to cover all of the request type so first we will have required or before we do that let me just make them all name parameter so we will have required request type and we will call it request type and then we will have required as well uri the url we want to send to uri and then i won't make this required however we will also send if we want to we can send map string string and we can call them headers and this might be nullable and also since we want this to be to cover other request types so i will also create something here so i will create a map string buddy sorry dynamic and we will call it body and this is also notable so we don't have to send it now let me just fix this all right now inside here what we will do we will check on the request type if request type is equal equal to requesttype.get since we only have get in this application we will say http dot get and first we will pass the uri we've created and then we've sent sorry and then we will pass headers which are the headers we sent now we will return this as well and now i will also i will actually copy this and i will i will not make it private i will make a function called send request and this send request takes request type as well and takes uri or we can send a string since our url is a string so let's call it url and we don't have to send headers we might create the headers here however i will take string here and i will create query param and instead of checking on all of these i will remove it and here we will create a send request so this send request will call the create request but this method is async so i will add async here and i will make this also this response also nullable now the first thing i will do i will create final underscore headers is equal to get headers and then i will create final url is equal to however this time before we do anything we need to con to concatenate the query param with the url we have so we're not going to do that in here we will actually create a new dart file and we will call it network underscore helper and inside here we'll create a class and we'll call it network helper sorry and we want this to be also a static class now inside i will paste the method that will create all of that we will call it concat url qp and then it takes a url and it takes map string query parameters now we will check if the url is empty we'll return the url also we will check if the query parameters are empty we will return the url otherwise we will create a string buffer with the url and also having a question mark because in the api link you can see that we have a question mark then we have the country which is equal to us then and api key which is equal to this key now let's come back here and then we will loop for each value inside this query parameter we will first check if it's empty we will return nothing and if it contains a space because it shouldn't contain space we will throw an exception invalid input exception otherwise if we don't have these two cases we will write on the string buffer that we created we will add to them key which is the key and the value which is key equal to value and then we will have end and after it finish we will get the result string buffer the two string normal string then we will return a sub string of this string of zero and resolve with length minus one and we are doing that because the last item or the last value in each in the parameter will have also this and and we don't want it so we will remove it by that now let's go back to the network service and we will say final url is equal to network helper dot concat qp we will send the url we have and we will send the query sorry the query parameters that we have now after it will create final response is equal to create request and inside here we shall send the request type which is request which is the request type we have and we will specify the url now uri is uri.bars the url we've created and concatenated and we will send the headers the headers we've created and here we don't have a body so that's it and we will add a weight here of course and also we will pass the body which is the body we've sent even if we don't have it in this tutorial now after it will just return the response and that's not everything we have to wrap this with dry catch so inside the throat we'll do all of that and in the catch we will get the exception and we will return first we'll print error and we'll print the error and then we will return null since this takes this is nullable now that's it for this class so let's go back to the network helper and let's create other methods or before we continue with network helper let's create a new dart file and let's call it network underscore enums and inside here i will actually paste these and here we have network response error type we have socket we have exception we have response empty and we have the did not succeeded and this could be from both ui or server and then i created another enum which is callback parameter name which has all and articles now let me explain something now let's go back to the browser and by all i mean everything inside the whole response with the status with the total results with articles and by articles i mean only articles since when we want to parse the data from the api to dartmouth we can't have status or total results or article we can only have list of articles so that's why i created all and i created articles and then i created an extension on the callback parameter name and it has a method called get json it takes json and if json is not a return null and otherwise we switch on this either all or article and if it's all we will return the whole json otherwise if it's article we'll return json articles so we don't type that ourselves we will have it in separate file now also before we continue with network helper let's also create a new dart file and let's call it network underscore type def and inside here since inside network service we are actually returning the response and i figured something that we are not using this url and we should be now we are returning this response and this response has body has a status code has everything and in network helper we're gonna decompose this response into whatever we want and then we will send it back however we're not always going to send it back or we can leave it since we want this to be generic we don't want we don't want to send it back ourself we want somewhere to have a call back so we can decide there what to do with the return data so that's why i created network type dev and inside here i will paste the methods that we will be using the callbacks i created type dev network callback which returns r and its function dynamic it will actually have the json or maybe true false boolean whatever and i also created typedev network and failure callback with message which is also r and this has two things the network response error that we created and string maybe we pass also a message so we could know the error if it's circuit error or exception or response empty or did not succeeded now that's it we can go back to the network helper and we can continue implementing it we will create a method that will hold all the api calls so we'll create it at static and it has r so static will call it filter response which also has r and inside here we will have required network callback and we will call it callback and we will also have required http and we haven't imported http yet so let's import it import http http.http now we will have http response however this response might be null but we have to send that attended and i will also have required we will say required network on failure on failure callback with message so i will call it on failure callback with message and then we will have required callback parameter name and we will call it parameter name and it shouldn't be required we can set it from here call back parameter name that all as default and that's it now inside that we will have try catch block since we might have an error inside here however in the catch we will not print at this time we will return the on failure with first we will have to specify the type error so we will have it as network response error type dot exception and we can specify a message here saying exception exception with the e now inside here first we will check on the response if response equal equal null we will also return on failure now this time we will have network response error dot empty response and we can have a message as empty response okay now we have to also check on the body so if the response is null or response dot body dot is empty so we will do that now below this since we are returning i'll create var json is equal to json decode and we will decode the response dot body and now first we will check on the if response dot status code is equal to 200 which means we have successfully called the api and we have valid result or we have result from the api so first we will check if if this result is valid and to check if this result is valid we will we're going to have to create a new method so let's create bool and let's call it as valid response and it takes the json okay now inside here we can return json different from null and and json i think this was called result if i'm not mistaken no status if status is equal to okay so we'll check on that so we'll check on json status different from null and and json status equal equal to okay now this is enough because if we want to make this generic we have to stay with this however if we want to make it uh particular for this api or for this result we have to also check and and if json articles is not null and i think that's all right now now inside here and we'll make this private in the in the network helper we only want the filter response to appear and concat ur now here will check is valid as valid i don't know why it's not helping so i will copy it as valid and i will pass the json now if it's valid now i forget to add static and that's why it was complaining now it's if it's valid we will return call however inside the callback we will say callback or parameter name actually dot get json with the json we have now that's not everything we also have to check inside here i think if status or response that status code is equal equal to 1708 i think this is a circuit error so we will return on failure network error and we'll use socket this time now we don't have a message or we can just say socket okay and i think that's all for this method and that wasn't everything we just have to return error in case uh we don't have any of these ifs so this error will be didn't succeeded and it's actually unknown so if we have this this means something is going wrong either on the api or our code now that's it for this network helper so let me close it and network service and query api network let me close everything i just want to have the article widget now inside here we will actually create final article and we'll call it article and i will add it to the constructor and i will make it required now instead of having background color we will have background image first we will check on the article dot image url different from null if it's different from null we will have network image with the article dot image url and what's okay we have to remove this const and we have to unwrap this okay and otherwise we'll just return null we don't want to have background image if if if the image is not sorry and then here in the text here we will have the author so article the title sorry here we will have the title and we will first unwrap it and here i think here we would have article dot author and just remove the cons from here and have it for the textile instead and down below here we would have article dot source dot name and otherwise we'll just have nothing and just remove this const from here and have it here instead and have constituents to your coins to here now we will have the const here actually we don't want it for the whole text now i'm not gonna here we will have publish add but publish ad if i showed you i'm not sure you can see that we have published at t and the time we don't want the time we only need the date so i'll create here inside this build method i will create final published at which is equal to article dot published at the split and we will split on the t and we will take the first part and let's just have a question here now i will use this publish that here otherwise i don't want to show anything and that's it for this widget now we have to go to the main and we have to implement a future builder so let's create it all right now in the body of the scaffold i will actually paste the future builder and i will have this and this so let me just show you what do we have here now we don't have yet this method get data we will create it in a while so we are checking on the snapshot if it's done and it has data we are having final list of articles from snapshot data as list of articles and then we are having list of viewers builder and we are calling the article widget for each item in the list of view builder and if it has error we're just returning center with column and icon and some text otherwise we are returning circular indicator progress indicator now let's create this method and this is future and let me just give you a little bit of space so you could see better all right this is a future list of articles and it might be null as well so inside here we'll say get data and doesn't take anything now the first thing we will do we'll say final and this is async as well we'll say final response is equal to network network service dot send request now the request we want to send we want to have request type as request type dot get and the url we want to send it is static values dot api url and then that's not everything we also have to send query parameters and query parameters we will send it as qp dot sorry qp dot api qp and we have to pass the api key which is static values dot api key and we have to send the country which is also static values dot api country and that's it but we have to await this as well now that's it we have the response and now if you want to we can print for example sorry response dot status code we can do that but better what's better we can say return network helper dot filter response and before we say what do you want to do with the callback first the response is the response we've created the callback i will create it in a while now on failure it takes error type and it also a message as a string now inside here we can return null and before it we can print it if you want but this would be duplicate however let's print it error type let's say error type and message as message and let me just fix this e all right now just have a semicolon here and i don't think we have to avoid this or we can okay now in the callback i will actually sense this returns a list and if we just send filter response with that we will have an error because the callback parameters or ram name callback parameter name are actually all however we want it to be an article so now we can if you want to you can say json and you have access on the json you can print it however i don't want to do that i will actually create a new method inside here i will create list and this returns list of article and i will call it list of articles from json and this takes json and we will return we will say first json as list and then here we will have that map and map e for each item inside this json we will return article article from json and we will pass the e and we will say as map string dynamic and just finally after it the to list and that's it now instead of doing anything on the callback i'll create this callback so now if we run it hopefully everything will work so let's turn on our emulator and let's run it and hopefully we don't have an error and we don't thankfully everything work fine and in a while it will load the network images and as you can see we have the title we have the author we have the name and we have the date and that's everything so thank you guys for watching and if you like the video make sure to subscribe and like and comment down below and i will see you in the next
Info
Channel: Coding Orbit
Views: 24,823
Rating: undefined out of 5
Keywords: flutter, flutter tutorial, flutter call api, flutter rest api, flutter calling an api, flutter calling rest api, flutter call rest api, flutter netwok service, flutter call api best practices, flutter consume api, flutter consume rest api, flutter http, flutter consume rest api with best practices, learn flutter, flutter network service implementation, flutter implement network service, flutter consuming rest api, flutter consuming api
Id: 04j8jTJ7j8Q
Channel Id: undefined
Length: 31min 26sec (1886 seconds)
Published: Tue Feb 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.