dio
A powerful HTTP client for Dart and Flutter, which supports global settings, Interceptors, FormData, aborting and canceling a request, files uploading and downloading, requests timeout, custom adapters, etc.
Top Related Projects
A type-safe HTTP client for Android and the JVM
An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.
🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀
Android Asynchronous Networking and Image Loading
The easiest HTTP networking library for Kotlin/Android
Quick Overview
cfug/dio is a powerful and flexible HTTP client for Dart and Flutter applications. It supports interceptors, FormData, request cancellation, file downloading, timeout handling, and custom adapters, making it a versatile choice for handling network requests in Dart-based projects.
Pros
- Supports both Dart and Flutter platforms
- Offers advanced features like interceptors and request cancellation
- Provides easy-to-use FormData handling for file uploads
- Highly customizable with options for timeout, headers, and adapters
Cons
- Learning curve may be steeper for beginners compared to simpler HTTP libraries
- Documentation could be more comprehensive, especially for advanced use cases
- Some users report occasional issues with specific edge cases or platform-specific behaviors
Code Examples
- Basic GET request:
import 'package:dio/dio.dart';
void main() async {
final dio = Dio();
final response = await dio.get('https://api.example.com/data');
print(response.data);
}
- POST request with FormData:
import 'package:dio/dio.dart';
void main() async {
final dio = Dio();
final formData = FormData.fromMap({
'name': 'John Doe',
'file': await MultipartFile.fromFile('./image.jpg', filename: 'profile.jpg'),
});
final response = await dio.post('https://api.example.com/upload', data: formData);
print(response.statusCode);
}
- Using interceptors:
import 'package:dio/dio.dart';
void main() {
final dio = Dio();
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
options.headers['Authorization'] = 'Bearer token123';
return handler.next(options);
},
onResponse: (response, handler) {
print('Response received: ${response.statusCode}');
return handler.next(response);
},
));
}
Getting Started
To use cfug/dio in your Dart or Flutter project, follow these steps:
- Add the dependency to your
pubspec.yaml
file:
dependencies:
dio: ^5.1.0
-
Run
dart pub get
orflutter pub get
to install the package. -
Import and use dio in your Dart code:
import 'package:dio/dio.dart';
void main() async {
final dio = Dio();
try {
final response = await dio.get('https://api.example.com/data');
print(response.data);
} catch (e) {
print('Error: $e');
}
}
This setup allows you to start making HTTP requests using dio in your Dart or Flutter application.
Competitor Comparisons
A type-safe HTTP client for Android and the JVM
Pros of Retrofit
- More mature and widely adopted in the Android ecosystem
- Extensive documentation and community support
- Type-safe API definitions with annotation-based approach
Cons of Retrofit
- Limited to Java and Android platforms
- Steeper learning curve for beginners
- Requires more boilerplate code for simple requests
Code Comparison
Retrofit:
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
Dio:
Response response = await dio.get('/users/$user/repos');
Summary
Retrofit is a robust HTTP client for Android and Java, offering type-safe API definitions and extensive community support. However, it's limited to Java-based platforms and can be more complex for simple requests.
Dio, on the other hand, is a powerful HTTP client for Dart and Flutter, providing a simpler API and cross-platform support. It's more lightweight and easier to use for basic operations but may lack some of the advanced features and type safety that Retrofit offers.
Choose Retrofit for Java/Android projects requiring type-safe APIs and extensive customization. Opt for Dio in Dart/Flutter projects or when simplicity and cross-platform support are priorities.
Pros of Volley
- Developed and maintained by Google, ensuring high-quality standards and regular updates
- Built-in support for request prioritization and cancellation
- Seamless integration with Android's AsyncTask for background operations
Cons of Volley
- Limited to Android platform, lacking cross-platform support
- Not as performant for large data transfers or file downloads
- Less flexible for customization compared to Dio
Code Comparison
Volley request:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Handle response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
Dio request:
try {
Response response = await Dio().get(url);
// Handle response
} catch (e) {
// Handle error
}
Dio offers a more concise and modern syntax with async/await support, while Volley uses a callback-based approach typical of Java. Dio's code is generally more readable and easier to maintain, especially for complex request scenarios.
An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.
Pros of android-async-http
- Specifically designed for Android, offering optimized performance for mobile applications
- Extensive documentation and a large community, providing better support and resources
- Built-in features like request cancellation and automatic retries
Cons of android-async-http
- Limited to Android platform, lacking cross-platform compatibility
- Less active development and maintenance compared to dio
- Heavier dependency footprint, potentially increasing app size
Code Comparison
android-async-http:
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://api.example.com/data", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// Handle success
}
});
dio:
Dio dio = Dio();
dio.get('https://api.example.com/data').then((response) {
// Handle success
});
Key Differences
- Language: android-async-http uses Java, while dio uses Dart
- Syntax: android-async-http uses callback-based approach, dio supports both callbacks and Futures
- Platform: android-async-http is Android-specific, dio is cross-platform (Flutter)
- Feature set: dio offers more modern features like interceptors and transformers
Conclusion
While android-async-http is a solid choice for Android-specific projects, dio provides greater flexibility and cross-platform support, making it more suitable for Flutter development and modern app architectures.
🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀
Pros of Fast-Android-Networking
- Specifically designed for Android, offering optimized performance for mobile apps
- Provides built-in caching mechanisms, reducing network calls and improving app responsiveness
- Supports both synchronous and asynchronous network operations
Cons of Fast-Android-Networking
- Limited to Android development, whereas dio is cross-platform (Flutter/Dart)
- May have a steeper learning curve for developers not familiar with Android-specific networking concepts
- Less active community and fewer recent updates compared to dio
Code Comparison
Fast-Android-Networking:
AndroidNetworking.get("https://api.example.com/users")
.addQueryParameter("limit", "3")
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// Handle response
}
});
dio:
final dio = Dio();
final response = await dio.get('https://api.example.com/users',
queryParameters: {'limit': '3'});
print(response.data);
Both libraries offer simple and concise ways to make HTTP requests, but dio's syntax is more modern and Dart-friendly. Fast-Android-Networking uses callback-based approach, while dio supports async/await for cleaner code. dio's cross-platform nature makes it more versatile for developers working on Flutter projects or targeting multiple platforms.
Android Asynchronous Networking and Image Loading
Pros of Ion
- More mature project with longer development history
- Supports both image loading and general networking tasks
- Offers more advanced features like caching and request prioritization
Cons of Ion
- Less active development in recent years
- Larger library size due to broader feature set
- May be overkill for projects only needing basic HTTP functionality
Code Comparison
Ion:
Ion.with(context)
.load("http://example.com/image.jpg")
.withBitmap()
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Dio:
await Dio().get(
'http://example.com/image.jpg',
options: Options(responseType: ResponseType.bytes),
).then((response) {
// Handle image data
});
Summary
Ion is a more comprehensive networking library with a focus on image loading and caching, while Dio is a lighter-weight HTTP client for Dart and Flutter. Ion offers more built-in features but may be excessive for simple projects. Dio provides a clean, modern API for HTTP requests in Dart applications, with active development and community support. The choice between them depends on the specific needs of your project and the platform you're developing for.
The easiest HTTP networking library for Kotlin/Android
Pros of Fuel
- Lightweight and focused specifically on HTTP networking
- Supports coroutines and reactive programming out of the box
- Extensive documentation and examples available
Cons of Fuel
- Limited to HTTP requests, while Dio supports multiple protocols
- Less actively maintained compared to Dio
- Smaller community and ecosystem
Code Comparison
Fuel:
Fuel.get("https://api.example.com/data")
.responseString { result ->
when (result) {
is Result.Success -> println(result.get())
is Result.Failure -> println("Error: ${result.error}")
}
}
Dio:
Dio().get('https://api.example.com/data')
.then((response) {
print(response.data);
})
.catchError((error) {
print('Error: $error');
});
Both libraries offer concise syntax for making HTTP requests, but Fuel uses Kotlin's Result type for handling responses, while Dio uses Dart's Future-based approach with then() and catchError().
Fuel is more Kotlin-centric and leverages language features like coroutines, while Dio is designed for Dart and Flutter ecosystems. Dio offers a wider range of features and protocols, making it more versatile for complex networking needs. However, Fuel's simplicity and focus on HTTP may be preferable for projects with straightforward networking requirements.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
dio
Language: English | ç®ä½ä¸æ
This is the base repo of the dio project. Please move specific paths for project instructions.
Don't forget to add #dio topic to your published dio related packages! See more: https://dart.dev/tools/pub/pubspec#topics
Versioning
Before you upgrade: Breaking changes might happen in major and minor versions of packages.
See the Migration Guide for the complete breaking changes list.
To know about our compatibility policy, see the Compatibility Policy doc.
All Packages
dio
- dio: link
Plugins
- cookie_manager: link
- compatibility_layer: link
- http2_adapter: link
- native_dio_adapter: link
- web_adapter: link
Examples
Copyright & License
The project and its underlying projects are originally authored by @wendux with the organization @flutterchina, started being maintained by Chinese Flutter User Group (@cfug) since 2023.
The project consents the MIT license.
Star History
Top Related Projects
A type-safe HTTP client for Android and the JVM
An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.
🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀
Android Asynchronous Networking and Image Loading
The easiest HTTP networking library for Kotlin/Android
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot