HighQ Dio
high_q_dio is a robust, production-ready, feature-rich HTTP client wrapper around Dio for Flutter. It implements advanced TanStack/React-style Query behavior, concurrent-safe token refresh mechanisms with circuit-breaker resiliency, request deduplication, and an advanced chunked resume uploader.
Features
- 🚀 TanStack Query Style Caching: Native support for query states, caching policies (
networkOnly,cacheFirst,staleWhileRevalidate), and tag-based automated cache invalidation. - 🔄 Robust Token Refresh Interceptor: Lock-secured concurrent refresh token handling, proactive refresh-ahead checks, and a circuit-breaker pattern to protect your auth servers during downtime.
- 🛠Pluggable Retry Interceptor: Configurable retry strategies, exponential backoff, and randomized jitter.
- âš¡ Request Deduplication: Suppresses multiple in-flight concurrent requests to the same endpoint and shares their responses.
- 🛑 Cancellation Manager: Simple manual cancellation and group request cancellation support.
- 📦 Resumable Chunked Uploader: Uploads large files in chunks with session tracking and automatic retries for failed chunks.
Installation
Add high_q_dio to your pubspec.yaml dependencies:
dependencies:
high_q_dio:
path: path/to/high_q_dio # Or hosted version
Run flutter pub get to download and install.
Quick Start
1. Initialize ApiClient
import 'package:high_q_dio/high_q_dio.dart';
final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com'));
// Token manager configuration
final tokenManager = TokenManager(
initialTokenStore: const TokenStore(
accessToken: 'initial_jwt_token',
refreshToken: 'initial_refresh_token',
),
onPersist: (store) async {
// Save tokens securely to Flutter Secure Storage / SharedPreferences
},
);
// Setup background refresh logic
final refreshInterceptor = DioRefreshInterceptor(
dio: dio,
config: DioRefreshConfig(
tokenManager: tokenManager,
authHeaderProvider: const BearerAuthHeaderProvider(),
onRefresh: (client, store, cancelToken) async {
final response = await client.post('/auth/refresh', data: {
'refresh_token': store.refreshToken,
});
return TokenStore(
accessToken: response.data['accessToken'],
refreshToken: response.data['refreshToken'],
);
},
shouldRefresh: (response) => response?.statusCode == 401,
),
);
// Initialize Client
final apiClient = ApiClient(
client: dio,
refreshInterceptor: refreshInterceptor,
cacheEngine: LRUCacheEngine(maxEntries: 100),
deduplicator: RequestDeduplicator(),
cancellationManager: CancellationManager(),
languageProvider: () => 'en', // Set dynamic Accept-Language
);
2. Make GET/POST Requests
// GET Request with Caching Strategy
final result = await apiClient.get<Map<String, dynamic>>(
endPoint: '/users/profile',
parser: (json) async => Map<String, dynamic>.from(json),
config: const RequestConfig(
cacheStrategy: CacheStrategy.staleWhileRevalidate,
cacheDuration: Duration(minutes: 5),
tags: ['profile'], // Tag for invalidation
),
);
result.fold(
(failure) => print('Error: ${failure.message}'),
(data) => print('Profile Data: $data'),
);
// POST Request that invalidates Cached Profile tag
final postResult = await apiClient.post<Map<String, dynamic>>(
endPoint: '/users/update',
parser: (json) async => Map<String, dynamic>.from(json),
config: const RequestConfig(
body: {'name': 'New Name'},
invalidateTagsOnSuccess: ['profile'], // Automatically invalidates cached profile
),
);
3. Request Cancellation
final cancelToken = CancelToken();
apiClient.get<Map<String, dynamic>>(
endPoint: '/some-long-request',
parser: (json) async => Map<String, dynamic>.from(json),
config: RequestConfig(cancelToken: cancelToken),
);
// Later, cancel request if user navigates away
cancelToken.cancel('User navigated away');
Example Project
An interactive simulation dashboard is included in the example/ folder, showcasing GET/POST caching policies, simulated token refresh flows, and real-time event logs.
To run the example:
cd example
flutter run