You don’t need to keep reinventing the wheel in flutter; there’s such a community that shares their pieces of code and functionality. These pieces of code are called packages, and today I am going to show you where you can find these packages, how to install them in your project, and lastly, how to use them by using the http package as our example.
This is the official package repository website for Dart and Flutter. You can search here for all the packages you need to speed up your development process by not coding everything from scratch but by utilizing the existing codes and features that others in the community have already built.
Now, try to search for “http” as I will demonstrate how to install and use that package.
After you search for it, go to the “installing” tab, and you’ll see instructions on how to install it. In my case, I’ll open a terminal on Visual Studio Code and type “flutter pub add http”. This will install the “http” dependencies and automatically execute the command “flutter pub get” to apply the dependencies.
You can see in the image below that the “http” package has been added in the
We can now import the “http” package into our project and use it.
Now for my example, before I am going to use the “http” package functionality, I am going to introduce to you first a useful tool for fetching fake data, perfect for prototyping and testing, which is called jsonplaceholder.typicode.com. I am going to get a json request from this website.
Http Package Usage
Now that all of the installation and tools are prepared, let’s get started using this “http” package.
First, I am going to create an async function because the “get()” function of the “http” package needs to be in place of an async function, and since we are requesting a response, I am going to assign it to a Response class utilizing one of the http package classes. By the time I wrote this blog, I could not just pass a string url to the “get()” function, so I used the Uri class to parse the string to a URI that is allowed to be accepted as a parameter for the “get()” function.
If I try to print the response body, it will successfully fetch the fake data from the JSON response.
I already taught you where to find flutter packages, how to install them, and how to use them. The JSON response on the visual studio code debug console print is not a map but a string representation of an object. That is why, if we want this data to be flexible for our use, we will convert it using a function called JSONDecode. Keep following me. I will show you in the next blog post how we can utilize the data for our project needs.