API Call in Flutter Mobile App Using Dio

In modern mobile applications, consuming RESTful APIs is an essential task. Flutter, being a cross-platform framework, offers several packages to handle HTTP requests. Among them, Dio is one of the most powerful and easy-to-use libraries.

In this Post, we'll explore how to make API calls in a Flutter app using the Dio package, covering setup, GET and POST requests, file upload and error handling.

API Call in Flutter Mobile App Using Dio

Getting Started

In Dart programming (especially in Flutter apps), the dio package is a powerful HTTP client used for making network requests. It's one of the most popular libraries for handling REST APIs and provides a rich set of features that go beyond the built-in http package.

dio is a high-level, feature-rich HTTP client for Dart, developed primarily for Flutter apps but usable in any Dart environment.

Key Features of Dio Package

  1. Request/Response Interceptors – Useful for modifying requests (e.g., adding tokens) or logging.
  2. Global Configuration – Set base URLs, headers, timeouts, etc., globally.
  3. FormData Support – Easily send form data, especially useful for file uploads.
  4. Cancel Requests – Support for cancelling HTTP requests.
  5. Timeouts – Connection, receive, and send timeout configuration.
  6. File Downloading – Built-in support to download files with progress.
  7. Error Handling – Structured error handling with clear exception types.
  8. Request Queue and Retry Mechanism – Helps with request retrying strategies.

Installing dio Package

Add it to your pubspec.yaml file:
dependencies:  
  dio: ^5.0.0 # Check for the latest version  

Then run:
dependencies:  
  flutter pub get 

Check for latest version of dio Package

API Call Examples

Here are some API call examples using the dio package in Dart programming (commonly used in Flutter apps). These include GET, POST, error handling and more.

GET Request
 import 'package:dio/dio.dart';  
 void main() async {  
  final dio = Dio();  
  try {  
   final response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');  
   print('Response data: ${response.data}');  
  } catch (e) {  
   print('Error: $e');  
  }  
 }  

POST Request
 import 'package:dio/dio.dart';  
 void main() async {  
  final dio = Dio();  
  final data = {  
   'title': 'foo',  
   'body': 'bar',  
   'userId': 1,  
  };  
  try {  
   final response = await dio.post(  
    'https://jsonplaceholder.typicode.com/posts',  
    data: data,  
   );  
   print('Created post: ${response.data}');  
  } catch (e) {  
   print('Error: $e');  
  }  
 }  

PUT Request
  Dio dio = Dio();  
  try {  
   Response response = await dio.put(  
    'https://jsonplaceholder.typicode.com/posts/1',  
    data: {  
     'title': 'Updated Title',  
     'body': 'Updated body',  
    },  
   );  
   print(response.data);  
  } catch (e) {  
   print('Error updating post: $e');  
  }  

DELETE Request
 void deletePost() async {  
  Dio dio = Dio();  
  try {  
   Response response = await dio.delete('https://jsonplaceholder.typicode.com/posts/1');  
   print('Post deleted: ${response.statusCode}');  
  } catch (e) {  
   print('Error deleting post: $e');  
  }  
 }  

Adding Headers (Bearer Token Authentication)
 final dio = Dio();  
 dio.options.headers['Authorization'] = 'Bearer your_token_here';  
 final response = await dio.get('https://api.example.com/data');  

Handling Error
 try {  
  final response = await dio.get('https://api.example.com/data');  
  print(response.data);  
 } on DioException catch (e) {  
  if (e.type == DioExceptionType.connectionTimeout) {  
   print('Connection Timeout');  
  } else {  
   print('Error: ${e.message}');  
  }  
 }  

File Upload
 import 'dart:io';  
 import 'package:dio/dio.dart';  
 void uploadFile() async {  
  Dio dio = Dio();  
  File file = File('path/to/your/file.png');  
  String fileName = file.path.split('/').last;  
  FormData formData = FormData.fromMap({  
   'file': await MultipartFile.fromFile(file.path, filename: fileName),  
  });  
  try {  
   Response response = await dio.post(  
    'https://your-api.com/upload',  
    data: formData,  
   );  
   print('Upload successful: ${response.data}');  
  } catch (e) {  
   print('Error uploading file: $e');  
  }  
 }  

If you want to know how to make a API call using http package then visit this post 'Making API Call In Flutter Application'

Summary

Using Dio in Flutter provides a structured and powerful way to perform API operations. With its extensive features and simplicity, it’s a great tool for building modern, scalable applications.

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال