network_cache_interceptor 2.0.0 copy "network_cache_interceptor: ^2.0.0" to clipboard
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:
    • GET requests are now cached by default, even if cache: false is explicitly specified.
    • Introduced uniqueWithHeader parameter, allowing differentiation based on request headers.
    • Introduced unique_key parameter for more precise cache invalidation per request.
    • Authorization and User-Agent headers are now ignored when generating cache keys to prevent unnecessary cache invalidation.
    • Improved unique_key handling 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: Authorization and User-Agent headers are ignored when generating cache keys.
  • unique_key Support: 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! πŸš€

8
likes
0
points
396
downloads

Publisher

unverified uploader

Weekly Downloads

NetworkCacheInterceptor is a custom interceptor designed to optimize network requests by integrating caching functionality into your application using the Dio library.

Homepage
Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

dio, flutter, path, sqflite

More

Packages that depend on network_cache_interceptor