network_cache_interceptor 2.0.0
network_cache_interceptor: ^2.0.0 copied to clipboard
NetworkCacheInterceptor is a custom interceptor designed to optimize network requests by integrating caching functionality into your application using the Dio library.
Network Cache Interceptor #
Network Cache Interceptor is a custom Dio interceptor designed for caching network requests. It returns cached data when offline and optimizes network request handling.
π¦ Installation #
Add the following line to your pubspec.yaml:
dependencies:
network_cache_interceptor: ^2.0.0
Or install it using flutter pub add:
flutter pub add network_cache_interceptor
π Whatβs New in Version 2.0.0 #
- Enhanced Caching Logic:
In version 2.0.0, caching has been improved with the following updates:GETrequests are now cached by default, even ifcache: falseis explicitly specified.- Introduced
uniqueWithHeaderparameter, allowing differentiation based on request headers. - Introduced
unique_keyparameter for more precise cache invalidation per request. AuthorizationandUser-Agentheaders are now ignored when generating cache keys to prevent unnecessary cache invalidation.- Improved
unique_keyhandling for better cache management.
π Usage #
1. Configure Dio #
import 'package:dio/dio.dart';
import 'package:network_cache_interceptor/network_cache_interceptor.dart';
void main() {
final dio = Dio();
// Attach the interceptor
dio.interceptors.add(
NetworkCacheInterceptor(
noCacheStatusCodes: [401, 403, 304],
cacheValidityMinutes: 30,
getCachedDataWhenError: true,
uniqueWithHeader: true,
),
);
}
2. Make a Request #
All GET requests are now cached by default, but you can still override caching behavior using extra['cache']:
final response = await dio.get(
'https://jsonplaceholder.typicode.com/posts',
options: Options(
extra: {
'cache': true, // Explicitly enable caching
'validate_time': 60, // Cache validity time (minutes)
},
),
);
To disable caching manually:
final response = await dio.get(
'https://jsonplaceholder.typicode.com/posts',
options: Options(
extra: {'cache': false}, // Disable caching
),
);
3. Using unique_key for More Precise Cache Invalidation #
The unique_key parameter allows more precise control over cache storage and retrieval.
It is useful when the same request may return different results based on dynamic parameters.
final response = await dio.get(
'https://jsonplaceholder.typicode.com/posts',
options: Options(
extra: {
'cache': true,
'unique_key': 'user_123', // Ensures this request gets a unique cache key
},
),
);
This ensures that responses are cached separately for different unique_key values.
4. Clear Cached Data #
Clear all cached data from the database:
final cacheInterceptor = NetworkCacheInterceptor();
await cacheInterceptor.clearDatabase();
βοΈ Configuration #
| Parameter | Description | Default Value |
|---|---|---|
noCacheStatusCodes |
Status codes that should not be cached | [401, 403, 304] |
cacheValidityMinutes |
Cache validity duration (in minutes) | 30 |
getCachedDataWhenError |
Fetch cached data when offline | true |
uniqueWithHeader |
Differentiates cache keys based on headers | false |
unique_key |
Custom key to uniquely store/retrieve cache | '' (optional) |
π§ Technical Details #
- Caching Logic: If there's a network issue, previously cached responses are automatically returned if available.
- Header Filtering:
AuthorizationandUser-Agentheaders are ignored when generating cache keys. unique_keySupport: Allows more granular cache control by separating responses.- Improved Error Handling: Better handling of network failures with enhanced logging.
- Data Storage: Cached data is stored locally using an SQL database.
π― Example #
final dio = Dio();
dio.interceptors.add(NetworkCacheInterceptor());
try {
final response = await dio.get(
'https://jsonplaceholder.typicode.com/posts',
options: Options(extra: {'cache': true, 'unique_key': 'session_abc'}),
);
print(response.data);
} catch (e) {
print('Error: $e');
}
π‘οΈ License #
This project is licensed under the MIT License.
π¬ Additional Information #
For more information or to contribute, visit our GitHub page.
Stay updated on new releases and project announcements! π
π¦ Check Out My Other Packages #
If you find this package useful, you might also be interested in:
- Telegram Bot Crashlytics - A comprehensive error logging package that sends application crashes and errors directly to a Telegram chat.
Stay connected for more powerful and easy-to-use packages! π