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: ^1.2.4
Or install it using flutter pub add:
flutter pub add network_cache_interceptor
π Whatβs New in Version 1.2.4
- Updated Caching Logic:
In version 1.2.4, the caching logic has been enhanced. All GET requests are now cached by default, even ifcache: falseis explicitly specified. This ensures consistent caching while maintaining manual control through additional options.
π 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],
cacheValidityMinutes: 30,
getCachedDataWhenError: 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. Clear Cached Data
Clear all cached data from the database:
final cacheInterceptor = NetworkCacheInterceptor();
await cacheInterceptor.clearDatabase();
βοΈ Configuration
| Parameter | Description | Default Value |
|---|---|---|
noCacheStatusCodes |
Status codes not to be cached | [401, 403] |
cacheValidityMinutes |
Cache validity time (minutes) | 30 |
getCachedDataWhenError |
Fetch cached data when offline | true |
π§ Technical Details
- Caching Logic: If there's a network issue, previously cached responses are automatically returned if available.
- Error Logging: All errors are logged using
log(). - Data Storage: Data is saved 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}),
);
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! π