Chopper (Retrofit for Flutter) - #1 Basics - Dart HTTP Client Generator Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
working with restful api sand making HTTP requests is the bread and butter of almost every developer if you are coming from Android you probably know about retrofit iOS developers as I am told have the Alamo fire library on flower though you usually use the HTTP package which comes directly from the dart team or something like dial although these packages do an awesome job they still leave you working at the lowest level the question arises what can we flirt developers use to simplify our world with HTTP api's chopper hello welcome to resale coder this is the first part of the chopper series where you are going to learn how to use the awesome chopper library to simplify your work with HTTP API in Dart in this first part we are going to build an app which will take data from JSON placeholder API which will simply display multiple posts here inside a ListView and it will also show a detail of a particular post so the first part covers setup and basics and later on we are going to touch on things like interceptors and converters and then integrating with build value or maybe even JSON serializable so there is really a lot to learn here and be sure to check out the written tutorial from the link in the description where you can also find all of the code written in this video and links to the libraries as always we are starting off in a clean new flutter project so we have only the main de dart file with the default code here so we need to set up our project to work with chopper for that we want to go to puff spec yamo and add a bunch of dependencies here the first thing which we are gonna add is chapter actually the latest version is two point four point one s of their date of recording and of course link to the libraries are all available in the written tutorial but adding chapter to just these dependencies is not enough because chopper is a library which generates code so in addition to adding chopper we also need to add the chopper generator which will actually facilitate the cogeneration and usually you put your generators not into dependencies but into dev dependencies so that they do not get back together with the app once you build it and ship it to your users devices because users really do not care about some builder they only care about the chopper library itself so we want to add chopper generator here and also build the runner and to use the latest version of the build runner you just leave the version empty this will make sure that you always have the latest version of that particular package and lastly in addition to chopper itself we are going to use the provider package to make inherited widget syntax simple because this app is only centered around showcasing chopper we are now going to have a full-blown state management over here but still we want to keep things nice and tidy even though we're now going to solely focus on state management if you want to learn more about state management check out a video about block because block is in my opinion the best state management option for flutter so let's add provider here once we save and the packages are gotten from the servers we can get to working with API as I've already said the API we are going to work with in this tutorial series is JSON placeholder because it is really simple to use and it's just perfect for our demonstration purposes so go to JSON placeholder type echo comm and over here we can see some of the things we can do with it for example down here if i zoom in we can see that the endpoints are posts comments albums photos to do users we are only going to use the posts endpoint so if we click on pose here or even down here we can get multiple posts which returns a JSON every pose has title and body this is what we are the most interested in and then we can also get just a single pose like that and also we can post two posts we are going to post posts even though this is only a placeholder API so nothing can be really added to these posts but still the pose request is possible and then you can also do put and badge and delete requests as you wish once we know which kind of an API we are gonna be working with let's create a chopper service because that's where most of the code regarding chopper will reside we are going to create a new folder under label let's call it data just to separate our classes a bit and inside that data folder we're going to create post API service dot dart and this file will hold post API service which will extend choppers service so let's add a class post API service which will extend chopper service and let's import chopper service by importing chopper package and we want to make this class abstract that's because as you already know by now chopper works by generating code and the actual implementation of this class will be inside a generated class not directly inside of pose API service that's why we can afford or actually have to make this class abstract actually in order to make the code generation possible we need to create a part statement here and this will direct the generator of the code to a file which will be sort of an accompanying file to this post API service dot dart main file the file which we are going to specify here is where the generated class will be so let's say post API service dot chopper dot dart and of course currently we have errors here because that file doesn't it exists but it will be generated in just a little while in order to make this class actually work with chopper we need to mark it with an annotation same chopper API so add chopper API and this takes in a base URL so what is the base URL for what we are trying to accomplish here well is the URL for the JSON placeholder API more precisely for the posts endpoint so let's go again back to the browser and where we are getting all of the posts we are going to copy this URL and paste it over to vs code as I have already briefly outlined what we want to do is to get all of the posts to display them inside a list to get only a single post to display the detail page of the post and also to perform fake post requests to basically just call post on the server but nothing will be really added but this is what this floating action button with the plus icon will do fake posting of the posts so for that we need to create three dart methods which will represent the three HTTP methods which we are going to call on that HTTP API so the first function is get posts and the question arises now what should this function return' well it's going to return a future but this future needs to contain something right and that something for now is simply a response this is absolutely not typesafe the response will just hold dynamic thing but later on in this series but later on in this series you are going to learn how to work with chopper in a type safe way so for example if we create some model like this class post which will hold that string body and string title and so on we'll be actually able to put a post over here inside response post like this we're gonna leave it for later just know that something like this is possible you can actually achieve really simple and straightforward type safety with the chopper API for now let's work with dynamic data because this is only the first part after all but just creating this method gateposts is not enough because this is only a dart method but we need to indicate to the chapel service which kind of an HTTP method it should actually represent the method we are talking about here is get so we need to mark it with AD get and it can take in headers and also they have we do not need to specify any headers nor any path because this get requests get post will happen directly on the base URL so we can leave the constructor empty then another method is get post in singular so again future response response get post and this will again be the get annotative method but this time we want to specify its path to be a string containing ID but this ID is dynamically assignable for that we need to put it inside curly braces in the string that's because getting the single post happens by specifying its ID so if we go to the browser just a quick demonstration here we have the first pose with ID 1 if I change the URL to end with two and not one we're gonna get the second post then three we're gonna get the third post and so on in order to change the ID dynamically we need to put the ID inside curly braces and now how are we going to actually pass that ID into the string to make the proper request well we need to specify a parameter int ID but not just like this simply we also need to annotate this parameter ID with a path and notation so again add path and we also need to specify string here IV so what this annotation add path will do is that oh I am annotated with add path with IV name so whatever the value of this int ID is I'm going to pass it over to the path in the URL and also this is a good place to mention query parameters since we are now going to use them in this app but if you have an API which requires you to work with query parameters we just specify add query and also its name here so for example Q and then you add for example string and its name and doing this will take this string and turn it into a query parameter in the request we are however not going to use any query parameters so we can just delete what I've just written and lastly we're going to perform a post request which again will return future response so let's actually just copy it from up here and it's gonna be called quite funnily post post and this will take in a body but we first need to mark it with add post and of course put and patch requests and the lead requests are done in the same manner you just annotate them so put and patch but again we are now going to use them here and also delete you can add delete too of course but we want to have just get get and post and post put and batch requests require that you put a body inside them and this body will contain the post which we are trying to add to the server the way that you can get some data some object to the server using HTTP is by putting it over to the body of the request so let's annotate it with body and the object which we are going to send to the server will currently be only a map containing string and dynamic that's because we currently don't have any post type and a post class but again later on we are going to add type safety to this app for now let's just work with map of string dynamic and let's call it body we have specified everything for code generation to work but before we generate the code let's just focus for a while on something which I want to showcase here because again we're now going to use it in this simple demonstration of an app but in your real projects you might want to use headers headers are simply a way to pass additional data to the server bundled in the request for example authentication is where the data is sent through headers and obviously also many other things so if you want to work with headers you can either add them to the method annotation here so we will just specify headers and it's going to be a map containing the name ABC and value may be CBA and then you can also add headers to the dart method itself this can be done by annotating with header in here you need to specify the headers name so again header name and the value of a header which is specified inside the parameter list is inside the parameter itself so for example string header value so inside the method parameters you specify some changeable headers which can change their value and the headers specified inside the annotation are useful for non changeable headers for example content type when it is for example plain text or text plain as it's properly formatted so to explain this is the perfect place for a constant kind of a header you can take a deeper look at this from the written tutorial which is available from the link in the video description but simply just note that this is also possible headers are also available if you use the chopper package with this additional information about headers out of the way we can now generate code which will be placed inside post API service that chopper dot dart source generation or source gen is triggered if we go into the terminal and write flutter packages Bob run build runner with an underscore and then you can either build for a one out built or also watch and watching will perform a new build each and every time a file with this part directive is updated it's saved with something new contained inside of it so let's say watch and hit enter and the new file will be generated called pose API service that chopper dot dart and surely after some time we have the new file over here if we take a look at it it contains a constructor which takes in a chopper client and then it has all of the methods which we have specified and they contain their implementation which we absolutely do not have to deal with the methods which we have written inside the post API service to specify what to fetch but all of the fetching logic would we'll actually trigger the HTTP request is contained inside chopper client this chopper client which we can even see that it needs to be passed into the constructor of post API service is built on top of the default HTTP client which comes from the dart team if we take a look at that we can see that it uses the HTTP client from package HTTP dot dart what we need to do in order to use the post API service to simplify our work with the JSON placeholder API is to somehow connect it together with the chopper client bypassing the chopper client over to the generated classes constructor basically we need to instantiate the chopper client the best place and the most elegant way to do this is directly inside post API service inside a static function called create which will return a post API service which is already set up with the client together with the generated class and all of that good stuff so we'll be able to call these three methods these three nice simple methods from the code in other places of our app so that other places will not need to worry about any of the implementation details about how HTTP requests are made our classes will simply be exposed to just these three methods so let's create a static function which will return post API service and it's gonna be called create and over here we want to instantiate the client first so final client is equal to chopper client and this chopper client takes in also a base URL but we have already specified the base URL over in the chopper API and notation well a good practice is to use the base URL over in the client like this so here should be just the URL ending with the top level domain com for example and then the different end points are gonna be specified inside the chopper API and notation this is good to do because now if you use another end point like for example comments or users you can just create multiple services for them but still use it with the same chopper client so let's switch back to posts other things which the chopper client takes in our services this needs to be a list and the service which we want to pass here is the generated class post API service and it's called with an underscore the dollar sign post API service this is just to let the chopper client know which kind of services it's gonna work with and then finally we're going to add a converter here and for now we're going to leave it at the default json converter which converts data to and from json and as the application json header for the content type later on in this series you're gonna learn how to add your custom controller so that you make the type safety possible with your favorite library whether it be built value or json serializable everything can be done with chopper so let's save so that it gets nicely formatted here and finally we want to return from this function the generated post API service with the client passed in this way calling the static method create will return a fully set up and initialized post API service instance this is all we are directly gonna do with Chopper in this first part now what's left is to build the UI since this is not a tutorial focused on UI I will go a bit faster now I will not type all of the code if you wanna check out the UI code in more detail at your own pace you can get it from the link in the video description inside main that dart we're going to select every and delete it and I'm gonna use awesome flower snippets to create material app definitely get the extension awesome flower snippets if you don't have it already it's really awesome and with that we are going to delete the scaffold from here so that it doesn't clutter up our code instead we're going to specify home page which is currently not present yet we're going to create it in just a bit home page will display the list of all posts more importantly what we want to do is to wrap the whole material app with a provider so instead of returning material app we're just going to copy it from here or actually cut it and return provider so let's import the package provider and provider is a simple way to facilitate inherited widget it takes in a builder which is a function taken in a build context and whenever you do not need a parameter you can just name it with an underscore to save space and this provider will provide the post API service to all of the widgets down the weather tree and since this provider will wrap the whole material app every single page and widget in our app will be able to access the post API service to make HTTP requests and how do we create a post API service well it's simple we're just gonna use the create method on it so post API service imported here and we just want to call create and that's it but just calling create is not enough we also need to handle what is going to happen on disposed if you are not using provider you would do this disposal obviously inside the state full widgets dispose method but since we are using provider we have a shorthand here we do not need to use stateful widget and inside this post which takes in also a context and then post API service service which is the instance instantiated in the Builder we want to call service the client which is the chopper client that disposed this will release all of the now unneeded resources and finally we are going to specify the child to be the material app and let's move over to home page we're gonna create a new file home page dot dart so just briefly on the home page its first going to add all of the import statements also for the single post page which we are going to create in just a little while and the class home page which is a state less widget actually will hold first the floating action button which whenever it's pressed it's going to access the post API service from the provider and it's going to call post post method with some fake data key value pair simply a map this is the function inside post API service which we have created which takes in a map annotated with a body it returns a future containing a response and since we cannot really add new posts to the database on the server because it's only a placeholder API we are simply going to print whatever is inside the responses body this will print it to the console what's important to remember here is this syntax provider off specify the type of post API service this is how we are always going to access our API service whenever we try to access it from the widgets of our app having the post request performed we are now going to move on to the body of the scaffold which will be built inside a separate function build body that will contain a future builder because this body will contain if you remember the list of all posts this is Ganon by calling the get request on API since all of the methods returned futures containing responses we are gonna use a future builder inside the body because future builder is perfect for easily building UI when awaiting a future and the object held inside future is response so as soon as built body is being built we wanna call get posts on the post API service and specified as the future of the future builder and then whenever the state of the future changes this builder of the future builder will run and here if the connection state is done which means that the future has already ended and the data was successfully gotten from the server over to our app we want to access the JSON string contained inside the response which came from the server if you are not sure where the response is actually located inside this builder snapshots data is the response this snapshot aceing snapshot is holding a response so data on the snapshot is of type response dynamic and this data representing the response we can access many things including a body string but also we can access the base response body bytes headers which were sent together with the response from the server and also the status code so for example 204 ok or 404 not found and so on response contains all of these kinds of things so snapshot data is the response we want to access its body string and convert it using the JSON decode into some manageable dart objects because we can now work with JSON strings directly we need to convert it first to dart objects and of course again we are missing type safety here the we are only converting it into a list dynamic later on you are going to learn how to use real dart types so that you don't just work with dynamic data which can lead to a bunch of errors down the line especially in bigger apps and once we have the list of posts we are going to build them inside a separate method called build posts this will return a list view and the posts are passed in here as a parameter we obviously need to specify the item count for the ListView which is the length of the post list and then we are getting to the interesting stuff we are specifying the item builder and all of the posts will be displayed inside a card which will hold a list style and here we set the title and subtitle of the list style to be a text and we get to the title and the body of the post because every single post has a title and a body and because we are only inside a list dynamic we need to trust that we are not gonna get any runtime errors that's the nature of dynamic but even through this dynamic mess which we are going to fix later on in this series we can get the particular index inside the list because we are inside an item builder which passes down an index and then we want to access the title as a map and also the body can be accessed by specifying the key for the map and finally this list style can be tapped which is going to call navigate to post and navigate to post will be a method taken in an ID and the posts ID can also be accessed on the post map because every post in addition to title and a body also has its ID over in the JSON object here and we are going to use this ID to specify the ID for the get request to get only the single post if you remember we have set up an ID parameter for the get post method and this is precisely where we wanna get that ID passed in fetching of the single pose will happen inside single post page so this is it for the home page let's actually import it inside main down dart so that we do not have an error here and now we can get to the single post page so let's again create a new file single post page the dart and this will be really quick we just need to import all of the packages here and then the single post page stateless widget will take in a post ID through the constructor because we want to use this post ID inside the build method inside the future builder once we get the post API service through the help of the provider we're going to call get post on it and passing the particular post ID which comes from this field and then again we are inside a future builder so we need to specify the builder and once the future is finished and all of the data is successfully gotten from the API we again access the response as the data of the async snapshot because again data is the response and we get its body string which is the JSON string and we call JSON decode then whatever is returned by this JSON decode we put it inside a post map so again dynamic data here I know it's ugly it's bad but we are going to fix it later and also if I haven't mentioned previously in the home page if the connection state is not done we display a circular progress indicator even inside the home page here just so that the user knows that something's going on in the background and then inside built post we simply create a column containing two text widgets which display the post title and the posts by this was just a quicker run through the UI so if you want to get through it at your own pace be sure to read the written tutorial available from reso called or combine on the link in the video description also over there is the full source code available from github now we can launch the app by hitting f5 and here we go we have a functional app which displays those 100 posts inside a ListView and we can click on an item inside the ListView and it's going to perform an additional post or get request to get the single post and we can also click this plus floating action button and it's going to print inside the console the value returned from the API and it seems that the response from the API is simply whatever we have passed in through the request because inside home page we are posting a simple map containing key and then value key value pair and then it also adds an ID 101 to that key value pair which we have sent in so this is the response printed over here inside the floating action buttons unpressed function so if we try once more yeah it always responds with key value and IV is 101 this is it for the first part and if you do not want to miss the next part of this chopper series on flutter definitely subscribe to this channel and also hit the bell button so that you are going to join the notification squad and not miss any of my new tutorials and other videos because here on reso coder I am determined to provide you with the best app development tutorials and resources out there if this video helped you give it a like and also share it with other developers remember that the written tutorial together with all of the code and the project files is available from the link in the video description an reso coder com leave a comment if you have anything to say follow me on Instagram face and Twitter and see you in the next video [Music]
Info
Channel: Reso Coder
Views: 42,948
Rating: undefined out of 5
Keywords: resocoder, tutorial, programming, code, programming tutorial, flutter, flutter sdk, flutter dart, flutter chopper, flutter retrofit, flutter http request, flutter http, flutter http post, rest api, flutter rest api, flutter rest api tutorial, flutter networking, flutter networking library, flutter networking example, flutter http request json, flutter json, flutter json api
Id: zFXK5EsrUF0
Channel Id: undefined
Length: 35min 33sec (2133 seconds)
Published: Wed Jun 19 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.