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
- Request/Response Interceptors – Useful for modifying requests (e.g., adding tokens) or logging.
- Global Configuration – Set base URLs, headers, timeouts, etc., globally.
- FormData Support – Easily send form data, especially useful for file uploads.
- Cancel Requests – Support for cancelling HTTP requests.
- Timeouts – Connection, receive, and send timeout configuration.
- File Downloading – Built-in support to download files with progress.
- Error Handling – Structured error handling with clear exception types.
- 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