Mastering API Calls in Flutter: Converting Data to Models and Handling Exceptions Like a Pro

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to our Channel developers today we have an exciting topic to discuss calling apis with Dio and creating models and we will also see how to handle HTTP exceptions in this video we will learn how to make HTTP request using Dio a powerful HTTP client for that and handle exception effectively so let's Dive Right In to get started we need to set up our Firebase project that I have already did and it's running make sure you have a flutter installed and create a new project open the project in your preferred code editor whatever you want like various code or Android Studio it doesn't depends now let's add some necessary dependency so inside your pubspec.tamil add this diode dependency I will provide the link to this dependency in description you can also copy from here and paste it there okay so after adding the dependency in your cop spec.tml file save the file and run flutter Pub get to face the dependency or you can click here if you want or directly you can control save you can control s you can do it will automatically do upgrade for you like this now let's create a DOT file called apservice.dot for calling or handling the apis so I will go here and create a folder called API and inside this I will create sorry I will create a API service file inside this I will create a class called API service and to call the HTTP methods or HTTP API first we need to create the instance of our dios I will create the instance of our dial as well so this can be a local so I will create a final dial instance so we need to import diode and after this we will create a Constructor for handling for calling the diver functions inside this we will create a named Constructor inside this I will create a instance of this class instance equal to API service.net okay so now we will create a function called Fetch data to fetch the data and one thing I forgot to say I forgot to tell you that we will use uh req res APA this APA for our example purpose I will provide the link of this CPA also so this is a get method if you come here like currently it's calling the PIN so we will remove this and directly go to the website so this we will use for example and we will use this end point that is APA slash user and this is a get method okay we will also see how to create a post method how to call the Post method also so now let's deep dive and now what I will do I have created the if you remember if you see I have created the instance so I will use this instance and that apis get method so what I will do I will copy this click here and copy the end points paste it inside the path section and now you can see that some question mark and page number is given this is called query parameters forget method so for this we need to pass and this can be passed inside a field called query parameters and inside this we need to pass the map and our key should be pitch because this API required a key called page and its value so this we can pass using query parameters if that is a get and if that is a post we need to pass this thing in our data like this so currently we are using get so we will pass inside the query parameters it will automatically encode in this form so now the page value should be 1. as you can see here it is using 2 because this is a paginating API so in later videos I will create how to do page Nation with JPS also so please subscribe to our Channel now what I will do I will wait for the calling like I Will Wait unless until it calls successfully and I think I okay so now after waiting it will give us a response that I will hold inside the response variable so now our API is called and whatever coming from the eBay it will come inside this response variable this response variable so we will use this response variable to convert the data eBay data in a form of model later in this video currently we will see whether the API is called or not okay so let's check whether it called or it's not calling so we will print this like this so this is error because I need to update the material.class and now inside the main dot dot I'll call the US APA that is inside the API service so API service dot instance data we have created and then the face data so let's check whether our eBay is calling or not see this API called successfully you can see here the result is coming so now our API is called successfully so in this way you can call the API inside of flutter it doesn't matter that whether it is get or post just use the method whatever given to you like if they pay uses post method use post if you replay users get get delete delete it totally depends upon the method that the API uses just pass the just use that function and that's it okay and something you need to remember that if you are using post then you need to use data instead of query parameters and if you are using get then you need to use Query parameters okay so now this is the thing that this is the whole procedure to call an API okay so in the above code we have created APS service class so let's elaborate again so in the above code in this code we have created API service class with a method called Fetch data okay and inside this method we used diode to make a get request that we have created here the response that is we can also check the response one thing I forgot to say but I will say right now we can also check the status code here like if the status code some whenever you call the API it returns some status quo like 200 200 for 20140 400 404 these type of status code it sends you okay so this status quo tells about the API call whether it's successful or it got an error so I will put the link of the sum status code like if you go to the Google and search status sorry HTTP status codes then you can get here first one website that is created in Mozilla only so these are some Response Code that can be returned by the server so what we need to check we need to check for only one response code that is 200 if the response code is 200 that our API call is successful we have successfully called the APN data is coming from the API okay we can also check the status code but in the later video we will I will tell you you don't need to check this you can directly check whether the issues happened or you can handle the exception easily okay so I will not going to check this or I will remove this and now now let's move on creating the model and converting the data that is coming from this API in a model class okay in a form of model so what I will do I will create a folder inside SRC and I will create a model called user model dot dot okay so now if you want to create a model you can do using three different methods there are three different methods you can use to create a model first one is to do it manually second is automatic and third is also automatic so if we move to the first one then it will take time but still I will show you suppose I need to create a model class then first I need to understand the structure of this APM like it contains a page that is form of integer per page form of integer total integer total page integer and then it contains the list of data so if I do it manually then at first I need to create a final integer whatever see model means whatever that is written here you need to do in the form of variables in there in the file okay so suppose I need to create the model of this file then I need to create a integer page final int total page and total and total page okay per page final line t total page and total correct and last we have a list of data that data is another form like it contains ID email first name last name and Avatar so I will create one more class called user data and then I will create same and integer ID final [Music] uh email final string all our string email first name last name Avatar and last one is our Avatar final string ever done Ctrl shift p now what you have to do you need to install these extension in your vs code uh second this extension that you can put here this dot data class simulator if there is a share button I will share this extension but I don't think you can share so just search here dot data class generator and install this that have more than one lakh installation and then what you need to do just con do Ctrl shift p and search for this property data class generator if that is not coming on the top don't worry just type dot data class generator and select second one okay now it will tell you which class you want to generate for which class you want to generate the model first I need to generate this user data okay so I will click here and okay okay so now he created the model of this class now what is spending in this one that the list of data and our the list of data is user data correct so what we will do we will create that list of user data and data and now we will create the instance of this API same and now we need to create the model for this user mod so now done one thing you need to remember that whatever the variable name is given here it should match here also if you don't provide this then you have to edit inside from Json from mapper from Json you need to update from map you need to update okay got it so these two need to be matched variable name and map if you are not matching it's not a big deal you cannot match also but the map that you are providing it should match with the repair data correct inside the map whatever the key that is given in the API you should match that the thing okay so this is the first method to create the API same thing we will create in a second okay so I will remove this and what I do I will copy this whole Json and paste it here sorry I think I haven't copied oh so okay wait one second and then I will copy this copy copy this and I will paste it here okay now what I will do I will do the same Ctrl shift p but now I will select generate from Json got it previously we selected generate from class properties now we will select generate from Json and we will type the class name what what we want we I want user model now it's telling me that you want to multiple files so why it's telling this suppose see what is happening that one branch is created after the data that is the list of map correct and here you can see One support is created a branch that is that is only a map so whenever a new Branch created inside digestion it will convert that branch in a new file so it's telling me whether you want to create a new file or you want to write all things in a one file got it so what I will do if I do this then it will create a model 3 Model inside this model class model folder sorry controls FP so let's check first what I will do I will save it and then I will do Ctrl shift p and from Json and I will put the name user model and now I want multiple files you can do no also it will create all classes in same file okay so I will do yes now you can see two classes are generated two dot files separate dot files as created and this is the thing if you select yes then it will create two different separate files if you click no in the same file it will create up multiple classes so now check check this same thing is there same thing that we have did manually is there correct another method to create a model is by visiting a website called json2 Dot this is the website I will provide the link of this website in the description what you can do you need to copy the same thing and then you need to paste it there sorry a copy and then I think paste it there okay correct so now you need to provide the name of this class it should be user model and then generate so now you can see that we have our uh data model ready so one thing you can see that in our data model that we have created using the Json contains final but and there is no null check also there is no null values also that it contains the null or not it's not seeing but here you can see there is no final and question mark is also not there that is null operator is also not there so what is difference between these two models these so these two models comes in a play when you have a dynamic UI if you are creating a final variable you cannot change it add that you cannot change it when it loaded correct you need to reload again to change the value whatever it is you cannot change it in the runtime you need to rerun or you need to go back and come again then you can do okay but here we can update values whenever we want like suppose I want to update this page so I can do with the dart code but this values but here we cannot do with the dart code because this is fine and final cannot change and if I want to update this then first you need to update inside the back end then it will come here okay and you need to refresh also this is the thing so this is the main difference and second difference is that it can accept null values also suppose sometimes what happens that DV returns a null value that the value doesn't exist and it Returns the null value for a specific field so it will support null also it it you can pass null also and your app will run smoother but here what will happen whenever you tries to give the null value your app will crash so these are the main difference that you want that you should remember before moving with the which thing which method you want to use so I have shown you all three methods and this is a perfect I think because you can update also and you can also use a null values correct but I don't want to use it right now I will use this one only because I have already created this and I have spent a lot of time I think around five to six minutes so I will not delete this okay so what you need to do copy this and paste it there if you want to use this you can copy this and paste it here same thing doesn't matter but that key difference is that it can accept null values and you can change the value ever whatever you what wherever you want okay so now we have created our user model class user model data data modeling we have done so now what we will do so now what we will do that now that we have our API service and model class ready so let's put them into action in our flutter correct so what we will do we will convert this data that is coming from this API in the form of models in the form of variables so how we will do like we will create a user model class first and then what we will do we will use a property Factory Constructor is there called from Json and inside this or we can use from map and inside this what we will do we will use response dot data this data contains the data that is coming from the API so now it's converted in a form of variables or the user model now our modeling is also done our API calling is also done so let's integrate this and show it inside our front end okay so what I'll do I'll go inside this million dot dot and then I will create a body here this should be a future Builder because our function is a future so to call the future better use future Builder and our function should have a type because function is returning something we will return it so this function will return a user model okay future user model okay so you will simply return future dot value user okay so now this thing is done till here so we will go inside this mean Dot and we have converted this future builder in a form of user model and inside this video Builder first it takes context and then snapshot of the data so now what I'll do first I will show the progress bar that it is loading circular progress indicator for it so now you will see here some circular progression correct so now I will check uh see suppose currently it's showing circular progress indicator that shows that our AP is loading wait yeah okay so now if the image is loaded what we will do we will use Snapshot dot hash data property that will tell whether that API has loaded or we got the data that is coming from the API and that is this function run is successful and return the value correct if it return the value it will fall inside this okay [Music] so now we will return list view because we have to build or show this list that data list in our front end correct so we will build a list view dot Builder and inside this Builder first it will take context and index and then we will return list tile got it and this should take item count and the item count is the data this is Snapshot that data is then this data will return this user model now we got the user model that is coming from here this user model we have got using uh using this snapshot.data got it so now if you remember if I have already shown you this data we need to be so we need to build this list of data so we need to find the length of this data correct so now if you remember I have told you right now this is Snapshot that data is a user model correct and inside this user model one property is called Data so if you remember I in the model class we have a data property this one got it this user model dot data has a list list of user user data that I will use the length property to find the length now we got the length of the data available available inside the user model or inside the APM so now first I need I will show a circle Avatar inside this I will render the user profile picture and then I will use title to build first name and last name and subtitle for got it so what I'll do I will go inside this and I will use leading property and circle lavator then I will use background image there should be a network image because we are dueling from Network now inside this we need to provide the URL so how we will get the URL so for what I will do what we need to think that first we need to go inside the user model okay then we need to access the data and then we need to go to Every index and when we go to the every index we need to access every Avatar correct so this is the step first we need to go inside the user model then in the data and inside the data section first we need to access every instance or every map and then inside every map we need to access Avatar got it so let's move with the steps that we have talked so for accessing the Avatar first we need to go inside the user model that is our snapshot dot data correct now we use inside we are inside the user model now now we need to go inside the data section of this user model that is the list of data correct now we have to access the every element that using the index property we can access every element so we have uh accessed individual element in a list now every individual element has a avatar so we will access this event that's it got it uh this is the thing that every element has a avatar property and if we look into our app that is still loading because we didn't provide it any future right until now so we will provide the future also because we want to see the changes so this is the fetch data method our fetch data method is inside this API service and we have created the instance if you remember and we're using that instance we have called AP got it so now let's refresh and check any issues are there or not let's check also on see this is the one exception occurred in our list sorry [Music] um model class that we need to handle also okay so now we are done with our part let's move into the user model and do some changes there okay so we will come here and go there and see whether which has the issue okay see see this data is normal not is mismatching with the data coming from jpg got it so we need to handle that exception also currently it's showing circular program as well so the user will know that our user will uh what think that the image is still loading we need to wait but exception again correct so we need to handle or show this inside this front end also correct so what we will do we will go inside this API service and we will use try catch first we will paste this and on exception it will catch the whatever the error is and then we will return the error with the future dot error so now what we will do go inside this mean the dot and then this future Builder has one property called snapshot dot has error so we will check if any error happened or not with the snapshot has error Boolean and now if any error happens it will we will return a center okay so if you remember we have provided one uh string while sending there this one so we will use this uh here by using a property called snapshot dotted got it so this will return us a variable so now you can see type Place Dynamic is not a type of list I will make it 20 and then title small to look better and also I will provide the padding and this text align should be Center that it looks good will look good now so now type Place Dynamic is not a type of so in this way you can handle internal errors or any model or mismatching errors happened while fetching the data okay so this is not a HTTP exception one thing you need to remember this is the internal error that is a model classer that you can handle or show whatever that exception occurred while parasing the values to different values while parsing operator to the model values correct next is that we need to solve this issue so we will go inside this model dot dot and and this should it's telling that type Dynamics are not a type of list so I will make it as a dynamic only and now I'll save it and if I refresh you can see our data is loaded what so in this way you can handle the internal issues got it so let's go further and create a title and email then after we will see how to handle HTTP exceptions yeah okay so now we will come here and then inside the title if you remember I have told you that we will show first the first name and last name now you have to tell me in comment that how we will show the title and first name and last name here okay I think you have written so match it pause this video if you haven't done right now and then you imagine it okay so this will help you to know that how we can use the data okay so now what we need to do if we go inside this model first we need to access the user model then the data and we need to access each element and inside this we need to access first name and last name same thing so what I'll do I'll create a thing snapshot.data gives user model then inside this data and then every element will be accessed by element dot index and then for we need first name um so this one okay see George is coming so if I want to show the last name also we can show okay so for showing the last name if you haven't typed retype it okay we need to wrap all this inside a string and then again we need to paste it down and now instead of this wait okay yeah non-stead of last first name we will use last name okay last name last name last name got it so George put and Janet Beaver so now now you just tell me how we can show the ml email put it in a description or comment section sorry put it in the comment section not in description so in this way we can call the API convert the period and form of model and then we can show inside the front end so now now let's move on to the HTTP exceptions okay or suppose this URL doesn't exist or any other exception occurred like this if we do this see okay this is showing earlier but this is not a character what I'll do see this is showing here the dial exception bad request the request returned an invite status code of 404 you can also handle this using this exception only but I will go further with this and what I'll do I'll create one more exception block called on Direct section uh die exception catch e so this will give this die exception will give the HTTP exception while calling the aps why you should use this but it can also done by this one so this will give you extra privileges like this e cannot be converted or this e and e has a different value this e is a dioception value but this is a common exception value and this expression value doesn't contain some of the variable that is given inside this type exception that will help you to give the user a better idea what has happened so that's why I have provided this like I will show you right now return future dot error e Dot message property is given you can also put like suppose you need to print the stack traces so you can put this actresses also debug prints actresses should keep stack dresses so I will provide stack traces e Dot tack traces got it so now if I come here you can see the stack dresses also that is coming here and if you remember in the previous you can only see this message now you can see the stack dresses like what happened why it's happened when it happened and what you need to do like this one you it's telling that whenever you are trying to call trying to call this it's giving 404 got it so in this way you can handles exception or HTTP exception in flutter application and show the data and convert the API data in form of models and show it inside of front and that's it by using diode to Quality and creating models with exception handles we have handled various scenarios while fetching and passing the data from remote server this ensure a smoother and more robust user experience feel free to experiment with different apis and customize the code according to your need whatever you want you can do if you found this video helpful please give it a thumbs up And subscribe to our channel for more exciting videos like this or this tutorial if you like it more uh insightful then you can share to your friends if you want thanks for watching and happy coding and one more thing I will tell you what next video you want you can tell me I'll create that so thanks for watching and we will see you in the next video
Info
Channel: Be Developers
Views: 709
Rating: undefined out of 5
Keywords: flutter exceptions, flutter efficient exception handling, api call in flutter, dart exceptions, flutter best practices, flutter series, api calls explained, flutter tips tricks, handling error, state management, socket exception, flutter efficient catching, flutter 3 tutorial, exception handling, flutter tips, get data from api flutter, flutter tutorial, exception, flutter tricks, flutter efficient, api calls, flutter 3, flutter 2.0, custom dialog, api in flutter in hindi
Id: dKyiahwOvgc
Channel Id: undefined
Length: 36min 36sec (2196 seconds)
Published: Thu Jun 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.