Flutter Dio Package

Powerful HTTP client for Flutter applications

⚡ What is Dio?

Dio is a powerful HTTP client for Flutter with interceptors, global configuration, request cancellation, file downloading, and timeout handling. It simplifies complex network operations with clean syntax.


// Import Dio
import 'package:dio/dio.dart';

// Create instance and make request
final dio = Dio();
final response = await dio.get('https://api.example.com/data');
                                    

Output:

Response: {"status": "success", "data": [...]}

Dio Key Features

🔌

Interceptors

Modify requests and responses

dio.interceptors.add(
  InterceptorsWrapper(
    onRequest: (options, handler) {
      // Add token
      return handler.next(options);
    },
  ),
);
⏱️

Timeout

Set connection timeouts

dio.options.connectTimeout = 
  Duration(seconds: 5);
dio.options.receiveTimeout = 
  Duration(seconds: 3);
📁

File Upload

Upload files easily

FormData formData = FormData.fromMap({
  'file': await MultipartFile.fromFile(
    filePath
  ),
});

Cancel Requests

Cancel ongoing requests

CancelToken token = CancelToken();
dio.get(url, cancelToken: token);
token.cancel('Cancelled');

🔹 Setting Up Dio

Add Dio to your Flutter project:

# pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  dio: ^5.4.0

Why Choose Dio?

  • Interceptors: Modify requests globally
  • Better Error Handling: Detailed error information
  • File Operations: Upload/download with progress
  • Request Cancellation: Cancel pending requests

🔹 Basic Dio Configuration

Create a configured Dio instance:

import 'package:dio/dio.dart';

class ApiService {
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: 'https://api.example.com',
      connectTimeout: Duration(seconds: 5),
      receiveTimeout: Duration(seconds: 3),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ),
  );

  Dio get dio => _dio;
}

// Usage
final apiService = ApiService();
final response = await apiService.dio.get('/users');

Output:

✓ Dio configured with base URL and timeouts

🔹 Using Interceptors

Add authentication tokens automatically:

class AuthInterceptor extends Interceptor {
  @override
  void onRequest(
    RequestOptions options, 
    RequestInterceptorHandler handler
  ) {
    // Add token to every request
    options.headers['Authorization'] = 'Bearer your_token';
    print('Request: ${options.method} ${options.path}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(
    Response response, 
    ResponseInterceptorHandler handler
  ) {
    print('Response: ${response.statusCode}');
    super.onResponse(response, handler);
  }

  @override
  void onError(
    DioException err, 
    ErrorInterceptorHandler handler
  ) {
    print('Error: ${err.message}');
    super.onError(err, handler);
  }
}

// Add interceptor
dio.interceptors.add(AuthInterceptor());

Console Output:

Request: GET /users

Response: 200

🔹 File Upload with Progress

Upload files and track progress:

Future<void> uploadFile(String filePath) async {
  FormData formData = FormData.fromMap({
    'file': await MultipartFile.fromFile(
      filePath,
      filename: 'upload.jpg',
    ),
    'description': 'My photo',
  });

  try {
    final response = await dio.post(
      '/upload',
      data: formData,
      onSendProgress: (sent, total) {
        int progress = (sent / total * 100).toInt();
        print('Upload progress: $progress%');
      },
    );
    print('Upload complete: ${response.data}');
  } catch (e) {
    print('Upload failed: $e');
  }
}

Output:

Upload progress: 25%

Upload progress: 50%

Upload progress: 75%

Upload progress: 100%

✓ Upload complete

🔹 Error Handling with Dio

Handle different types of errors:

Future<void> fetchData() async {
  try {
    final response = await dio.get('/data');
    print('Success: ${response.data}');
  } on DioException catch (e) {
    if (e.type == DioExceptionType.connectionTimeout) {
      print('Connection timeout!');
    } else if (e.type == DioExceptionType.receiveTimeout) {
      print('Receive timeout!');
    } else if (e.response != null) {
      print('Error ${e.response?.statusCode}: ${e.response?.data}');
    } else {
      print('Network error: ${e.message}');
    }
  }
}

Possible Outputs:

✓ Success: {"data": "..."}

⚠ Connection timeout!

✗ Error 404: Not found

🧠 Test Your Knowledge

What is the main advantage of Dio over the standard http package?