Flutter beginners tutorial: Make HTTP requests to a REST API. Fetch data from the network.

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we are going to learn how to make http requests from a flutter app we are going to use a fake rest api and we shall make the different http request so you are going to learn how to perform the different operations on a rest api create read update and delete along with this you are also going to learn how to work with asynchronous functions in flutter so the first thing that we have to do to make an http request from a flutter app is to install the package http so run the command flutter pub add http on the terminal inside the root directory of your flutter project so here you can see that this is the default flutter app which gets created whenever you create a new flutter project so this is a new flutter project and here on the terminal inside the root directory of my flutter project i am executing this command flutter pub at http or you can go to pub.dev and search for the package http and follow the installation instructions now after installing this package we can start using the aps we have to import the corresponding library inside the file where we want to write the relevant code we are going to create a helper class a class where inside this class we are going to write different functions for perform the different http request so here inside the leap directory of the project let us create a new file new dart file named http helper inside this file we are going to create a new class named http helper and here let us create a few functions for the different http requests inside this class inside this file we are going to write the code related to http request so we are going to use the apis of the package http so here we have to import the package the library http dot dart now this library http dot dart has some top level functions like post gate etc corresponding to the defined http request and for convenience of calling them for clarity we can import this library using a prefix so here along with the import statement if we add as and then a word a string this will be used as prefix now we will be able to use this prefix to call the functions for example if we need to call the post function to make a post request we shall call http.post so this makes it clear that we are calling the function of the http library now let us create the different functions inside this class so let's create the first function for fetching all the items then we sell create one function for fetching the details of one particular item then we shall create one function to add a new item to the database then another to update one item and finally to delete one item all right so let's create the functions now the first function that we are going to create will be to fetch a list of items from the backend from the apa so in case of a to-do list this may be a list of tasks for a particular user in case of a blog or news app this can be a list of articles or list of posts so inside this function we are going to make an http request to the corresponding api and that api is supposed to provide us some kind of a collection of some kind of data some kind of item and then we are going to parse it and we are going to create a list of maps so basically we are going to convert the individual items to instances of map of the class map and then we are going to return that list of map from this function here instead of map you can use any custom object so in this case to keep it simple i'm going to use a map so the return type will be future of type list of map now list of map because we are going to get a list of map from this function but why this future so if you are wondering that then let me quickly give you an idea and i'll also add a link to a detailed tutorial in the description you can watch that after watching this video so in dart the class future represents the result of an sn cross function so first of all you have to understand the difference between a syncros function and an asynchronous function a synchronous function blocks the execution whereas an asynchronous function does not block the execution now imagine this function to be a syncross function this is not and this is going to be an asynchronous function but for a moment just imagine that this is a synchronous function and we have implemented it we have written the code to make an http call get the data parse the data and finally return the list of map and somewhere inside our code we are making a call to this function to get the data and below that call we are writing the code to display a loader to the user to indicate that we are getting the data make sense right now as this is a synchronous function the user is not going to see the loader during the process because this function here is going to block the execution until its completion so it will make the http request it will wait for the data it will get the data it will parse the data it will return the data and then only the code below it will be executed so the user will not be able to see the loader event the user will not be able to interact with the app the app will basically freeze because no other code will be executing during that time so this is not the expected behavior right and thus whenever a function needs to perform a long running task we have to make it asynchronous so if a function needs to make http calls if it needs to interact with the local database or the file system or any other long running task then we have to make that function asynchronous now if this were an asynchronous function this would not have blocked the execution so it will start executing this function parallely but it will not block the execution here so the code below it also will start executing so the user will see the loader and it will be able to come interact with the app and in the future whenever the data is ready inside this function it will notify us about that that the data is available or an error has occurred so we can take a look at that and we can get the data or we can handle the error and now in dart whenever you make you need to create an asynchronous function before starting the body you have to add the keyword async and that function has to return in future and the actual data which the function is going to return will be the type of that future so in this case our function is going to return a list of maps so this feature is going to be of type list of map now whenever we call this function this function will give us an instance of future immediately without any data so the future the instance of future is kind of a promise that some data will be available in future if no error occurs and if any error occurs the error will be available inside this instance of future itself so we have to keep looking at that future for the data now the function will start executing and without interrupting the normal flow of execution and whenever the data arrives whenever it parses the data and the data is ready then it will put that instance of list of map inside this future and if any error occurs then it will put the error inside this instance so we have to work with the future we have to take keep looking at it for the data or for the error and there are different ways to work with the data of a future we are going to explore some of them now here i have created a variable of type list stock map and i have initialized it with an empty list and we are going to make an http request here we shall get the data and we shall assign the result to this variable and finally we are going to return it from this function now let us create another function to get to fetch one particular item from the api let's name it get item and we are going to add one parameter here because we are going to pass the id of the item to be fetched the return type of this function is going to be future of type map because this is a single item we sell get the item we shall get the data of one particular item we shall create a map using that data that we get from the api all right so here let's create a variable of type map initialize it to an empty map we can create maps using this curly brackets right and then we are going to return this from this function and as this is an asynchronous function we are returning a future and we also have to use the keyword as sync before starting devotee here in this portion before returning we are going to make the http request to the api now let us create the function add item to add one particular item this function will get the map of data so we shall pass a map containing the data to be added to the database all right so we shall pass a map thus let's add a parameter of type map let's name it data and from this function we are going to return a boolean so we are going to return the status whether the update whether adding the item has been successful or some error occurred if it failed so we are going to return boolean now again this function is sn cross so this will be a future of type boolean and from this function we are going to return either true or false depending on the result of the api call so here let's create a variable of type boolean and in initialize it to false and below it we are going to make the http request and we shall get the result we shall check whether the whether the process has successfully completed or any error has occurred and then we say return the result now we are going to do something similar with the next function which is for updating one particular item so let's copy this code and paste it and now let's change the name to update item and this function will get this map with the data to be updated along with this map it is also going to have another parameter another string for the item id because we are going to update the information of one particular item right and to identify that item we have to use the id of the item again from this function we are going to return the status of the process so we are going to have this boolean and the return type will be future of type boolean similarly let us create the delete function so let's name it delete item this two is going to return a boolean so return tag will be future of type boolean and this will get the item id to be deleted all right so let's add the parameter item id and inside again we are going to perform the deletion operation and if is successful then we are going to return true otherwise false so here we are going to make the actual call to the api for deleting the item by this id now let us make the actual http request and for that we should have the api endpoints right so we should have some url where we can make an http call http request and that url should give us the data or perform some operation all right so in this case for this example we are going to use a fake api provided by the website called jsonplaceholder.typecode go there and here you feel you will find some fake api so we have fake aps for post to do user album comment etc we are going to use this one for the post so if you make a request to this url jason placeholder.typical.com slash post then it will give you a list of posts so this is json array inside we have some json objects and inside the individualization objects we have the data for a particular post some kind of a post all right so we are going to fetch we are going to make a get request to this url and we shall get the data we shall parse them and we shall display them on the ui all right similarly you can go to this link guide and you will find the instruction on making the other http request you how to fetch one particular item so you can make a request a get request to this url where you add the item id after post and it will give you the information the details of one particular item by this id similarly you can make a post request to add a data this is not going to do anything in the database because no database exists in this case these are fake data but it will give you a fake response whether the item has been added or not similarly to update data and to delete data you can make these requests and they will provide us some fake response so this is good enough for testing the functionality of our app to learn how to make http request from our flutter app all right so first of all we are going to make a get request to this url to get the get all of the items all right so let's copy this url and now let's go back to the code so this is this is the function where we are going to fetch all of the items right here we have to make a call to the function gate of this library http we are using this prefix to import it so we can make a call to the function using this prefix http.get to this function we have to pass a uri so we cannot simply paste the url in this way we have to convert it to a uri and for that we simply need to call this function parse of the class uri so uri dot parse to this function past the url so this is an asset cross function because this may take a little longer to perform its task right and thus it returns a future of type response so at the end of the operation we shall get an instance of this class response so let's create a variable to hold this response and we have to use the keyword await here to wait for its and we are getting this error because we have to use the keyword http to access it now you may be wondering what is this keyword await so let me tell you so this is an sn cross function right this gate is an s and cross function so this is not going to block the execution just immediately after starting the execution of this function gate even before it it completes the next statement will start executing which is not expected in this case inside this function right because we are going to return this empty list even before we have the actual response of the gate request so inside this sm cross function we want to wait for the completion of this function before executing the next statement make sense right so we have to make it behave like synchronous we have to block the execution here until the completion of this gate function this get request and we can do that using the keyword away so if you use the keyword await here it will wait until the completion of this function and then only it will proceed to execute the code below now this is going to block the execution inside this function only and wherever we are calling this function fetch item there as we are not using the keyword avoid and as fetch item is sm cross there it is not going to block the execution and the app will behave normally the app will not freeze the user will be able to interact with the app normally all right so inside this function it will wait for its completion because we need the data that we get from this function before executing the code below it all right and here as we are using the keyword await so we are waiting for the completion of this function thus we don't need the future we can get the actual data right so here when you use the keyword event you don't get a future you wait for the functions completion so you get the final data which is being returned from this function so here we can make we can create an instance of response to hold the result we don't need to create a future now if you take a look at the previous discussion here and if you use the keyword await before calling this function this true code will behave the same way and another important point you can use the keyword await only inside an asynchronous function now from this instance of the class response we can get the different information about the response we can get the status code we can get the data from it from this instance itself so we can check if the status quo is equal to 200 which means that the request has been successful without any error we have got some data or the data we may not have a list of items that is a different thing but the http request was performed without any errors so if the status code response the status code is 200 then we are going to get the data from the response and we can get that from the field called body of this class so response dot body will give us the data in form of a json string and we have to convert it to the type that we want in this case we are going to convert it to a list of maps and for that we are going to use a library called convert an inbuilt library of dart named convert this library has a function named this json decode we are going to pass this json string to this function json decode and this will give us a list of maps now here let us implement all of these functions at once and then we shall make calls to these functions from our widgets all right so let us implement the next function which is to get one particular item so again we are going to make a get request to a similar url if you take a look at the guide of the fake api then you will notice that we have to make a request to an url like this one we just have to add the id here all right so let's copy this and paste it here and we are going to add the id of the item to fetch we have the id from this argument right so here we are going to add it using string interpolation so we are making a call to this this url this base url then slash post slash the id of the item to be fetched then we are going to check whether this the request was successful we shall check if this status code is 200 if it is 200 then we are going to get the data from the field body of the response again again this is going to give us a json string we are going to convert it using json decode and this time json decode will give us a map so this is the response of this url slash post for getting all of the items right now if we add slash item id let's consider let's pass one here and enter then take a look at the response this is a single json string right this is not an array and if we pass this session string to the function json decode this will give us a map containing these key value pairs all right so we shall get a map and here we have created a variable of type map to hold this response right it is item not items and then finally we are returning this item from this function now let us implement this function add item to add one item so we have to make a post request to this url so the url is the same the base url slash posts and we have to make the post request so for getting all of the items we have made a gate request to this url to this url itself and to get one particular item we have made gate request but the url is a little different we have added the id2 right and now to add one item to make a request to add one item we have to make a post request to this url all right so let's call http.post and pass uri.parse then the url so we can copy this and paste it here and now we have to pass the data to the parameter body and this function two is going to return us an instance of the response so we are going to create a variable of type response to hold the result all right so we have to pass the data to the parameter body and we are going to pass it as session so we are going to call json encode and we shall pass this data to this function so this function json encode belongs to the library convert we have used json decode here right now we are going to convert this map to a json string and so we are calling json encode we also have to pass a map to the parameter headers and we are going to add one key value here for the content type we are going to pass application slash session to the field content type and now here too we are going to check if this status code is 200 which means that the request happens successfully without any errors then we are going to check if we have got a non empty response so if you take a look at the guide you will notice that this api for this this fake api returns the data that we have sent back to us indicating a successful edition of the item all right so this may be different in different api so you may have a defined api you may send either true or false depending on the result or something else but in this particular api it sends us back the data that we send to it all right so here we shall check if the data is non-empty and if it is not empty then we are going to return true so we are going to assign the value of response dot body dot is not empty to the boolean status so if this is not empty this will be true if it is empty this will be false we are going to return this boolean from this function now let us implement the update function and for that first of all let us take a look at the guide for the apa so you have to do that whenever you have to interact with an api you have to understand how the api works and for that you have to take a look at their guide right so here we have to make a request to this url so basically slash posts slash item id added to the base url right because we are going to update one particular item by its id right and then to the body we have to pass the data to be updated so here is the data so we are going to update this item by this id and we we shall pass the data which needs to be updated and we have to make a put request we have to pass the same header application slication and the response will be similar to the previous one so we shall get the data that we send back again in the response right let's go back to the code now so here is our function update item let's copy this portion of the code from the add item function because this is going to be almost similar we have to add the item id so let's add this item id that we get from this argument using string interpolation and we have to change this function we have to call put then we have to pass the data we are using json encode to convert this map to adjacent string and we are passing these headers all right and the response again will be similar so if it is 200 then we should get some data we shall check if it is empty or not empty if it is not empty then we are going to return true now finally let's call this delete function let's implement the delete function and for that we have to make a call a delete request to this url so again similar to the url we used for updating and getting one particular item because this time again we have to provide the id of the item to be deleted right so we have to make a call to this request and we have to make a delete request so here is our function we have to call http.delete let's copy this uri and paste it here so here again we have the item id from this argument so here we sell check if status code is 200 and if it is 200 then we are going to consider the operation to be successful so if it is 200 then we are going to make status true indicating that the item has been deleted successfully and then we are returning the status so this will be different from api to api right so now we have created the different functions to make the different http requests and now let us create the different widgets for the different pages of our app and from those widgets we are going to call these functions of our of our http helper class to far from the different operations so we shall create one widget for displaying the list of post another for displaying the details of one particular post then one to display a form to add a post and another to edit one particular post and now let us make this post list widget the home page of our app currently the default my home page widget is being displayed so here we are going to change it and we are going to pass an instance of our widget to this parameter home of the material widget inside the main.dart file now if you run the app you will notice that the the post list widget is being displayed as a home page at this moment this is blank this is black because we are simply returning a container from the build function of the widget now let us create the ui first of all we are going to return a scaffold from this build function and let's also add an app bar also we are also going to display some title on there but and to the body of this scaffold we are going to add an instance of an inbuilt widget named future builder which helps us in displaying data from a future and in this case we are going to get an instance of future by calling the function fetch items of our http helper class so here let's create a field of type future of type list of map to hold the future that we get by calling fetch items so whenever we call a an asynchronous function it immediately gives us an instance of a future and whenever the function completes its task it puts the data the final data inside that future and if any error occurs then it puts the information of the error inside that future so we can use the callback functions of the future class to get notified about these events of successful completion or error and then we can handle them accordingly but in this case we are not going to use the callback functions instead we are going to use the widget future builder to fetch and display data from a future so here to the body let's add an instance of the widget future builder here we also have to specify the type of data that we are looking for so let's add list of map here and we have to pass values for two of the parameters of this constructor of future builder so one is future another is builder so to the future we have to pass the future from which we are going to get the data and to the parameter builder we have to pass an implementation of a function and this function is actually responsible for creating the layout depending on the data that we get from the future data or error that we get from the future so here this function gets two arguments first is the build context and the second is an instance of a class called async snapshot this instance is going to give us the actual data or the error so there is a field called data from which we shall get the data and we can get the error from snapshot.adder if any error occurs now inside this function we are going to check whether any error has occurred that we shall check whether the data has arrived if none of them are true then we are going to display a loader so here first we are going to check whether snapshot.has error is true so this is true when some error occurs if it is true then we are going to return a text widget with the error message because we are going to display a an error message on the screen so the widget that you want to add to the widget tree has to be returned from this builder function so in case of an error we are going to return a text widget with the error message and to display the message at the center we are going to wrap this widget by the widget center then we are going to check if snapshot dot has data is true this is true whenever we get data whenever the data has arrived right and inside this we are going to get the data so as i have mentioned the data becomes available inside the field called data of the instance snapshot so snapshot.data in this case is going to give us a list of map so the data that we are looking for the data that future provides becomes available on this field data of the instance snapshot now as we have the list of items to be displayed let's use a list view to display them on the ui so we are going to use the constructor builder and to item count we are going to pass the number of items that we have inside the list and to the item bitler function we are going to provide the implementation of this function from this function we are going to return a list that and we are going to pass the title and subtitle to the parameter title we are going to pass the title of the post from the map from the individual map we can get the map using this index right and to the subtitle we are going to pass the body of the post so here inside this block if we have the data we are creating this list right we are using the listview to display the content in a list and if none of these are true then we are going to display loader so here add a return statement and return an instance of the widget circular progress indicator and to display the loaded progress indicator at the center of the screen wrap it by the widget center now save the changes and let's load the app but here we have got an error let's find out what has happened it says that list dynamic is not a subtype of list of map so this means that we are treating a list without knowing the type of item the list contains we are treating that list as a list of map so here inside the inside the future builder we are specifying the type here so this should not be an issue here let's take a look at the fetch item functions and here i think here we have made this message we have to cast the response that we get to a list of maps we have to cast the individual items of the list to map so here let's create a variable to hold this value that we get by passing this data to the json decode function and then we are going to call data.cast and here we are going to specify the type of the individual items as map and then we are going to assign this result to the variable that we have created items so this time this should work let's save this and here we have the list of posts now in a similar way let us implement the item details page so we are going to load this widget on tapping one item of the list so here inside the ontap function of the list diluted we are going to use the navigator to load that widget and inside this widget item details we are going to use a future builder because we are getting a future from the function gate item we have to call the function gate item right to get the details of one particular item so let's create a future here a field of type future and initialize it inside the constructor but this time we have to pass the id of the item to this function gate item to get the details of that particular item right so here let's add one field because we are going to pass that id from the list page to this page through the constructor so let's add a field here and initialize it through the constructor and then we shall pass it to this function now we are going to pass the id while create while loading this widget from the list page now inside the post detail widget inside the future builder inside the item inside the builder function of the future builder first we are going to check if any error has occurred if any error has occurred then we are going to display the error message if the data has arrived then we are going to get the data and we are going to create the ui to display the data and in this case snapshot.data will give us an instance of map because our future is of type map the function gate item returns a feature of type map so we are going to use a column to display two text widgets one the title and the second body so we are going to display these two information only and then we are going to return a circular progress indicator to display the loader right now save the changes and here we can see the details of the one particular post now let us implement the update item page so first we are going to add two icon buttons on this app bar of the details page on clicking one of the item button with the edit icon we are going to load the update item edit item page to display a form to update one particular item and on clicking the delete icon we are going to delete this particular post this particular item now inside the edit item widget we are going to display a form and on loading this widget we are going to pass the existing content inside a map from the details page to this page so we shall use them to pre-fill the text from fields of our form so we shall create two text editing controllers we shall initialize the value text of this in text editing controllers with the existing value existing information and then we are going to pass them to the corresponding text editing controllers all right takes form fields to the corresponding text formats and inside the on press function of the elevated button we are going to write the code to call the update item function of our http helper class because we have created that function to update the information of one particular item we have to pass the item id to and here inside this function we are already getting the data from the text form fields with help of the text editing controllers and we are creating a map we have to pass the data to be updated to the function in front of a map so here let's create an instance of the class http helper and call the function update item to the first parameter pass this map data to update and to the second parameter we have to pass the item id so here inside this widget we have the map called post which is holding the map which is being passed from the detail space and that map contains the id of the post against a field called id so we are going to get that value and pass it to this function and we are also converting it to a string by calling tostring now this function update item returns the future after boolean so whenever we call it it will give us a future and once it completes its task if no error occurs then it will put a boolean on the future indicating the status of the operation and below this statement we are going to write the code to check the status whether the update has been happened successfully or not and depending on the status we are going to display some kind of a message on a snag bar all right so we have to wait for the completion of this function before we can display the message right because we are going to check the status whether this had been this was successful or not and then only we are going to display the message to the user so for that we have to wait here until its completion then we will get the status the result the status and then only we are going to check the status and display the message so instead of getting the future and then using the callback functions we are simply going to use the keyword await here we have already learned about this right if we put the keyword away in front of an asynchronous function then it is going to behave in a synchronous way so it will wait for its completion before proceeding to execute the next code but there was an important point that i have mentioned you can use await only inside an asynchronous function so here we have to mark this function this on press function asynchronous by adding the keyword as sync before starting the body of the function so now this is an asymptotes function and inside this assume cross function exactly at this statement we are waiting for its completion and then we are proceeding to the next statement where we are checking the result of the previous statement and then depending on the result we are displaying the message to the user now save the changes load the app and let's try to update this information so let's make some changes and press this button and here on a snack bar we can see the message post edit post updated now let us also implement the delete functionality and for that inside this on press function of this icon button we are going to call the function delete item of the http helper class we have to pass the item id and here we have the item id inside this class itself so let's pass it and this will return a feature of type boolean does we are going to create a boolean to hold the result we shall use await to wait for its completion and if deleted is true then we are going to display a success message otherwise a message of failure save the changes and try clicking on this button and here we have got the message now finally let us add a floating action button inside the list page and here inside the on press function we are going to write the code to load the add post widget and i have added the i have created the ui for the add post widget we are going to display a simple form and inside the on press function of the elevated button we are going to write the code to add the new item to the database so now the form looks like this one we are going to add so here inside the on press function we already have the map to get the data from this input fields and then we are going to call the function add item of the http helper class we have to pass the map of the data to be posted and it returns a boolean a feature of type boolean does we are using this keyword avoid here and we are holding the result in this boolean status if status is true then we are going to display a success message post edit on a snack bar and if it is false then we are going to display the message of a failure now save the changes now let's try adding a post using this form so let's add some data here and press this submit button and here we have got a message of failure but why did it fail let's take a look at the class http helper so this is the function add item and here once we get the response we are checking if the status quo is 200 if it is 200 then we are returning true returning then we are checking whether it is empty or not and we are updating the value of status right but this let's try 2 0 1 here so a standard rest api returns the status code 201 in case of creating data all right so let's save the changes and this should fix the issue and here we have got the success message so with this we have learned how to make the http request to a rest api from a flutter app if this video has helped you then like this video subscribe to the channel and let's get connected on the comment section
Info
Channel: Droidmonk
Views: 10,801
Rating: undefined out of 5
Keywords: flutter, flutter tutorial, flutter http request rest api, flutter http + get post delete patch put, flutter http, flutter rest api, flutter rest api tutorial, flutter http post request, flutter app development, flutter tutorial for beginners, how to make http request in flutter, how to make network calls in flutter, flutter networking, flutter networking tutorial, flutter future, flutter future async await, flutter futurebuilder, How to fetch data from the internet in flutter
Id: VBWClV-w7q0
Channel Id: undefined
Length: 43min 20sec (2600 seconds)
Published: Wed Sep 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.