support Click to see our new support page.
support For sales enquiry!

How to Use REST APIs in Flutter with Dio?

How to Use REST APIs in Flutter with Dio

Nishma KVJune 30, 2025

As mobile developers, working with REST APIs is a fundamental part of building real-world applications. Flutter, being a cross-platform UI toolkit, offers a variety of options for network requests. Among them, the dio package stands out for its simplicity, power, and flexibility. 

In this article, we’ll explore how to use Dio for making REST API calls in Flutter — including how to structure your code, handle responses, manage errors, and follow best practices.

 


Why Choose Dio Over Other HTTP Clients?

While Flutter’s native http package is sufficient for basic use cases, Dio provides additional features that make it ideal for complex applications. These features include global configuration, interceptors, advanced error handling, request cancellation, form data handling, and much more. This level of control is especially useful in large-scale apps where consistent network behavior is critical.

To get started, Dio can be added to your project by including it in the   pubspec.yaml file and running:

flutter pub get 

 


Making Your First API Call

Once Dio is added, you can initialize a simple GET request with just a few lines of code. For example, if you're trying to fetch a list of users from a public API, Dio simplifies this process considerably. You instantiate a Dio object and call its  get()  method by passing in the API endpoint. The result is returned as a  Response  object, which contains the HTTP status code, headers, and data.

This abstraction helps keep your code clean while still allowing flexibility. Rather than embedding this logic directly in your UI, it's best practice to separate API logic into a dedicated service class — for example,  ApiService .

 


Structuring Your API Layer

For production-ready applications, separating concerns is key. You should keep your API logic away from UI code. A good practice is to create a service layer that handles all HTTP operations. This keeps your UI widgets focused only on presentation and user interaction.

A typical API service class might include methods like  fetchUsers() createUser() , or  deleteUser() , and each would internally use Dio to communicate with the backend. This structure improves maintainability, makes unit testing easier, and promotes reusability.

 


Error Handling with Dio

One of Dio's standout features is its robust error handling system. Instead of just throwing generic exceptions, Dio categorizes errors using  DioExceptionType , which includes connection timeout, send timeout, receive timeout, bad response, and others.

This allows you to customize your error handling logic. For instance, if a request times out, you can show a “Please check your internet connection” message. If the server returns a 401 status code, you can redirect the user to the login screen. Such fine-grained control is crucial for enhancing the user experience.

 


Adding Headers and Interceptors

In real-world scenarios, most APIs require authentication tokens to be passed in the headers. With Dio, this can be done globally using interceptors. An interceptor allows you to modify every request before it is sent. This is the ideal place to inject headers such as  Authorization or to log request and response data for debugging purposes.

For example, you can set an interceptor to automatically attach a bearer token to every request or refresh the token if the server responds with a 401 error. This avoids repetitive code and ensures consistency across the app.

 


Uploading Data and Making Other HTTP Calls

Dio supports not only GET requests but also POST, PUT, DELETE, and even file uploads. When making a POST request, you can simply pass the request body as a  Map<String, dynamic> , and Dio will handle the conversion to JSON. For file uploads, Dio provides a convenient  FormData class that supports  multipart/form-data  encoding.

This versatility means you can handle user registration, form submissions, updates, and deletions — all using a consistent API interface.

 


Best Practices for Using Dio in Flutter

To get the most out of Dio and maintain a clean codebase, consider the following best practices:

  • Use a singleton for your Dio client to avoid redundant initializations.
     
  • Centralize your base URL and headers in one place using Dio’s  BaseOptions .
     
  • Always handle errors gracefully and inform users when something goes wrong.
     
  • Separate your API layer from your UI to improve modularity and testability.
     
  • Use models to parse and represent data instead of working directly with raw JSON maps.

0

Leave a Comment

Subscribe to our Newsletter

Sign up to receive more information about our latest offers & new product announcement and more.