The best way to handle network requests in Flutter

Jiten Patel
Level Up Coding
Published in
4 min readNov 19, 2021

--

In my recent article called “Integrating APIs in Flutter” I talked about how we can integrate APIs in Flutter. I made use of the famous http package for handling network requests. But it has its own pros and cons. This article is the extension of my previous article if you haven’t gone through it please read it here before diving into this article.

In this article instead of using the http package, we will use the Dio package to handle our REST API and I will also show best practice to write a code for network handling in which we are going to create just one dart class (magic code) that can handle all HTTP requests (GET, POST, DELETE, PATCH) and that class file can be used in any type of project you create in a flutter. But before that what is wrong with the http package?

What’s wrong with the http package?

Flutter offers an http package that’s nice while performing basic network stuff but when you start working on a big application and we need to do something more advanced task, http package lacks at it. Your application might face lots of problems with network error handling. In that case, we need some advanced library that has some extra functionality like interceptors, log, cache, etc. and that’s where Dio comes in handy.

What is Dio?

Dio is a powerful HTTP client for dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout, etc. By comparing the http package with Dio, Dio provides an intuitive API for performing advanced network tasks with minimal effort.

Getting started

You can clone the app from my Github repo. If you wish to go along with this article you can do change in the master branch. If you want the final code just change the branch from master to dio. Let’s add dio to our project. Go to pubsec.yaml, under the dependencies, add the dio package.

dependencies:
dio:

Run “flutter pub get” to install the package. Now, head over to the services folder in which we already have one file called http_service.dart. Let’s make changes to this file.

The Magic Code

Delete the whole code which is written in our http_service.dart file and add the above code. Let me explain to you the code one by one. We have declared an enum called Method which holds all HTTP Methods (line no. 5). Inside HttpService class we have a static method called header() which has a configuration of a Content-Type. You can also add an authorization header to this method while dealing with authorization. Inside the init() method, we initialized our Dio instance with BaseOpotions which accepts the base URL and it has an optional parameter called header. We pass our previously written method header() to it (this is also called a function/method as a parameter). We also have interceptors that help us to log our requests, response, and error. I will go much deeper into the concepts of interceptors in other articles but here's a great article to understand what Interceptors are. The main important part to consider here is our request() method because that’s where all the magic happens. It accepts two required parameters and one optional parameter called url, method, and params respectively. The code is self-explanatory, we check the type of method and do the requests accordingly. We have also wrapped our code inside a try-catch block for error handling which throws exceptions according to the status code we received. On line number 74 we have DioError which is a class that helps to handle Dio errors.

Yeah! That’s it we are done with our magic code. You can take this code in any flutter project and handle any type of HTTP request.

Making changes in our project

While writing the above HttpService class you will encounter the errors in the product_controller.dart file too. Let’s make changes in this file too to make our app running.

Instantiate HttpService class (line no. 10). The only change we have to make in this file is in fetchProducts() method. Pass the required parameter i.e. url and method. As we have already mentioned the base URL in our HttpService class, here we just have to add the route which we have to hit. For example, here we have hit the “products” route. Pass “products” to url parameter. We are making a GET request so pass Method.GET to a method parameter (line no. 23–24). Check the result is null or not also check if the response we get is of Dio response. Finally, we update our product list (line no. 24–30).

Phew!

Final output

Gif by author

Conclusion

We wrote a magic code that help us to make any type of HTTP request and we also made a hands-on on a real application. Probably the best way to make a Network request. Isn’t it?

Link for GithubRepo:

Previous article:

Almost any article I write... I write them with love ❤️ and I make sure that every word makes sense to anyone around... If you find this helpful to you, then share it with your friends.. give it a clap, and a Github star ⭐

Have doubts? Let’s get connected on LinkedIn, Twitter, & Instagram

Happy Coding :)

--

--