Dio is a robust and flexible HTTP client for Flutter with support for interceptors, timeouts, and transformers.

1. Setup

yaml:

dependencies: dio: ^5.4.0

2. Basic Usage

Dart:

final dio = Dio();
Future<void> fetchData() async { try { final response = await dio.get('https://jsonplaceholder.typicode.com/posts'); print(response.data); } catch (e) { print('Error: $e'); }
}

3. Add Interceptors

Dart:

dio.interceptors.add(InterceptorsWrapper( onRequest: (options, handler) { options.headers['Authorization'] = 'Bearer your_token_here'; return handler.next(options); }, onError: (DioError e, handler) { print('Error status: ${e.response?.statusCode}'); return handler.next(e); },
));

4.  Use Retry Policies (Optional)

Use packages like dio_retry or implement custom retry logic.

5. Create a Dio Client Wrapper

Dart:

class ApiClient { final Dio _dio = Dio(); Future<Response> get(String path) async { try { return await _dio.get(path); } catch (e) { throw Exception('Network error'); } }
}

Pro Tips:

  • Set timeouts: connectTimeout, receiveTimeout
  • Always wrap responses in try-catch
  • Use enums or sealed classes for response types
  • Use flutter_bloc or riverpod for state handling