iws_cache 0.0.1
iws_cache: ^0.0.1 copied to clipboard
A flexible key-value cache library for Flutter with TTL support, multiple eviction policies, and both in-memory and persistent storage options.
IWS Cache #
A flexible key-value cache library for Flutter applications with TTL (Time To Live) support, multiple eviction policies, and both in-memory and persistent storage options.
Features #
- Dual Cache Implementations: Choose between in-memory cache for fast access or persistent cache for data that survives app restarts
- TTL Support: Automatic expiration of cached items with customizable time-to-live
- Multiple Eviction Policies: LRU, LFU, FIFO, LIFO, and Random eviction strategies
- Size Management: Configurable maximum cache size with automatic eviction
- Statistics Tracking: Comprehensive cache statistics including hit/miss ratios
- Metadata Information: Detailed information about cached items (size, access count, timestamps)
- Automatic Cleanup: Periodic cleanup of expired entries
- Type Safety: Generic get method with type safety
Getting started #
Add this package to your pubspec.yaml:
dependencies:
iws_cache: ^0.0.1
Then run:
flutter pub get
Usage #
Memory Cache #
Perfect for temporary data that doesn't need to persist across app restarts:
import 'package:iws_cache/iws_cache.dart';
// Create a memory cache with size limit and LRU eviction
final memoryCache = IwsMemoryCache(
maxSize: 100,
evictionPolicy: EvictionPolicy.lru,
cleanupInterval: Duration(minutes: 5),
);
// Store values with optional TTL
await memoryCache.put('user_profile', userProfile);
await memoryCache.put('temp_data', someData, ttl: Duration(minutes: 30));
// Retrieve values with type safety
final profile = await memoryCache.get<UserProfile>('user_profile');
final tempData = await memoryCache.get<String>('temp_data');
// Check if key exists
final exists = await memoryCache.containsKey('user_profile');
// Get cache statistics
final stats = await memoryCache.getStats();
print('Hit ratio: ${stats.hitRatio}');
print('Total items: ${stats.itemCount}');
Persistent Cache #
Data persists across app restarts using SharedPreferences:
import 'package:iws_cache/iws_cache.dart';
// Create a persistent cache
final persistentCache = IwsPersistentCache(
maxSize: 200,
evictionPolicy: EvictionPolicy.lru,
);
// Store values that persist across app restarts
await persistentCache.put('user_settings', userSettings);
await persistentCache.put('cached_response', apiResponse, ttl: Duration(hours: 24));
// Retrieve persisted values
final settings = await persistentCache.get<Map<String, dynamic>>('user_settings');
// The data will be available even after app restart
Advanced Usage #
// Get detailed item information
final itemInfo = await cache.getItemInfo('my_key');
if (itemInfo != null) {
print('Size: ${itemInfo.sizeInBytes} bytes');
print('Access count: ${itemInfo.accessCount}');
print('Created: ${itemInfo.createdAt}');
print('Expires: ${itemInfo.expiresAt}');
}
// Manual cleanup of expired items
final expiredCount = await cache.evictExpired();
print('Removed $expiredCount expired items');
// Change cache configuration
await cache.setMaxSize(50, evictionPolicy: EvictionPolicy.lfu);
// Batch operations
await cache.removeAll(['key1', 'key2', 'key3']);
// Clear all cached data
await cache.clear();
// Always close caches when done
await cache.close();
Using CacheService (Recommended for Apps) #
For production applications, use the CacheService singleton to manage cache instances throughout your app:
import 'package:iws_cache/iws_cache.dart';
// Get the singleton service instance
final cacheService = CacheService.instance;
// Use pre-configured cache instances
final memoryCache = cacheService.memoryCache; // Fast temporary data
final persistentCache = cacheService.persistentCache; // Data that persists
final apiCache = cacheService.apiCache; // API responses with long TTL
final userDataCache = cacheService.userDataCache; // User-specific data
// Store data in different caches based on use case
await memoryCache.put('session_token', token, ttl: Duration(hours: 1));
await persistentCache.put('user_settings', settings);
await apiCache.put('user_profile', profile, ttl: Duration(hours: 24));
await userDataCache.put('theme', 'dark');
// The same cache instance is returned every time
final cache1 = cacheService.memoryCache;
final cache2 = cacheService.memoryCache;
print(identical(cache1, cache2)); // true
// Cleanup when app shuts down
await cacheService.closeAll();
// Clear all caches (useful for logout)
await cacheService.clearAll();
// Get statistics for all caches
final allStats = await cacheService.getAllStats();
for (final entry in allStats.entries) {
print('${entry.key}: ${entry.value.itemCount} items');
}
Benefits of Using CacheService #
- Singleton Pattern: Same cache instances across your entire app
- Pre-configured: Ready-to-use caches for common scenarios
- Specialized Caches: Different caches optimized for different data types
- Easy Management: Bulk operations like
closeAll()andclearAll() - Statistics: Centralized monitoring of all cache instances
Eviction Policies #
Choose the best eviction strategy for your use case:
- LRU (Least Recently Used): Evicts items that haven't been accessed recently
- LFU (Least Frequently Used): Evicts items with the lowest access count
- FIFO (First In, First Out): Evicts the oldest items first
- LIFO (Last In, First Out): Evicts the newest items first
- Random: Evicts random items
final cache = IwsMemoryCache(
maxSize: 100,
evictionPolicy: EvictionPolicy.lfu, // Use LFU strategy
);
Example #
Check out the complete example in the /example folder that demonstrates both memory and persistent cache usage with a Flutter app.
Cache Implementation Comparison #
| Feature | IwsMemoryCache | IwsPersistentCache |
|---|---|---|
| Speed | ⚡ Very Fast | 🔄 Fast (disk I/O) |
| Data Persistence | ❌ Lost on app restart | ✅ Survives app restart |
| Memory Usage | 💾 RAM only | 💾 RAM + Disk storage |
| Initialization | ⚡ Instant | 🔄 Async (loads existing data) |
| Storage Location | In-memory only | SharedPreferences |
| Best Use Cases | Temporary data, session cache | User settings, API responses |
| Platform Support | All platforms | All platforms |
| Serialization | Not required | Automatic JSON serialization |
Choose IwsMemoryCache when you need maximum speed for temporary data that doesn't need to persist across app sessions.
Choose IwsPersistentCache when you need data to survive app restarts, such as user preferences, cached API responses, or offline data.
Additional information #
This package provides a clean, abstract interface (IwsCache) that both implementations follow, making it easy to switch between memory and persistent caching or even implement your own cache strategy.
Performance Considerations #
- Memory Cache: Fastest access, but data is lost on app restart
- Persistent Cache: Slightly slower due to disk I/O, but data persists
- Both implementations use efficient algorithms and automatic cleanup to maintain performance
Thread Safety #
Both cache implementations are designed to work with Flutter's single-threaded model. All operations are async and safe to use from the main isolate.