iws_cache 0.0.1 copy "iws_cache: ^0.0.1" to clipboard
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.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:iws_cache/iws_cache.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'IWS Cache Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const CacheDemo(),
    );
  }
}

class CacheDemo extends StatefulWidget {
  const CacheDemo({super.key});

  @override
  State<CacheDemo> createState() => _CacheDemoState();
}

class _CacheDemoState extends State<CacheDemo> {
  late final IwsCache memoryCache;
  late final IwsCache persistentCache;
  String _output = '';

  @override
  void initState() {
    super.initState();

    // Initialize memory cache
    memoryCache = IwsMemoryCache(
      maxSize: 10,
      evictionPolicy: EvictionPolicy.lru,
    );

    // Initialize persistent cache
    persistentCache = IwsPersistentCache(
      maxSize: 50,
      evictionPolicy: EvictionPolicy.lru,
    );

    _runDemo();
  }

  Future<void> _runDemo() async {
    final buffer = StringBuffer();

    buffer.writeln('=== IWS Cache Demo ===\n');

    // Test Memory Cache
    buffer.writeln('--- Memory Cache Test ---');
    await _testCache(memoryCache, buffer, 'Memory');

    buffer.writeln('\n--- Persistent Cache Test ---');
    await _testCache(persistentCache, buffer, 'Persistent');

    // Test persistence by creating a new instance
    buffer.writeln('\n--- Testing Persistence ---');
    final newPersistentCache = IwsPersistentCache();

    // Wait a bit for initialization
    await Future.delayed(const Duration(milliseconds: 500));

    final value = await newPersistentCache.get<String>('persistent_key');
    buffer.writeln(
      'Value retrieved from new persistent cache instance: $value',
    );

    await newPersistentCache.close();

    setState(() {
      _output = buffer.toString();
    });
  }

  Future<void> _testCache(
    IwsCache cache,
    StringBuffer buffer,
    String cacheType,
  ) async {
    // Store some values
    await cache.put('key1', 'Hello World');
    await cache.put('key2', 42);
    await cache.put('key3', [1, 2, 3, 4, 5]);
    await cache.put(
      'ttl_key',
      'This will expire',
      ttl: const Duration(seconds: 2),
    );

    if (cache is IwsPersistentCache) {
      await cache.put('persistent_key', 'This persists across restarts');
    }

    buffer.writeln('$cacheType Cache - Stored 4 items');

    // Retrieve values
    final value1 = await cache.get<String>('key1');
    final value2 = await cache.get<int>('key2');
    final value3 = await cache.get<List<int>>('key3');

    buffer.writeln('Retrieved values:');
    buffer.writeln('  key1: $value1');
    buffer.writeln('  key2: $value2');
    buffer.writeln('  key3: $value3');

    // Check cache info
    final itemInfo = await cache.getItemInfo('key1');
    if (itemInfo != null) {
      buffer.writeln(
        '  key1 info: ${itemInfo.sizeInBytes} bytes, '
        'accessed ${itemInfo.accessCount} times',
      );
    }

    // Get stats
    final stats = await cache.getStats();
    buffer.writeln(
      'Stats: ${stats.hits} hits, ${stats.misses} misses, '
      '${stats.itemCount} items, ${stats.totalSizeInBytes} bytes',
    );

    // Wait for TTL expiration
    buffer.writeln('Waiting 3 seconds for TTL expiration...');
    await Future.delayed(const Duration(seconds: 3));

    final expiredValue = await cache.get<String>('ttl_key');
    buffer.writeln('TTL key after expiration: $expiredValue');

    // Test eviction
    final evictedCount = await cache.evictExpired();
    buffer.writeln('Evicted $evictedCount expired items');

    // Final stats
    final finalStats = await cache.getStats();
    buffer.writeln(
      'Final stats: ${finalStats.hits} hits, ${finalStats.misses} misses, '
      '${finalStats.itemCount} items',
    );
  }

  @override
  void dispose() {
    memoryCache.close();
    persistentCache.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('IWS Cache Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Cache Demo Output:',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 16),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[300]!),
                ),
                child: Text(
                  _output.isEmpty ? 'Running demo...' : _output,
                  style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _runDemo,
        tooltip: 'Run Demo Again',
        child: const Icon(Icons.refresh),
      ),
    );
  }
}
0
likes
160
points
34
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A flexible key-value cache library for Flutter with TTL support, multiple eviction policies, and both in-memory and persistent storage options.

Homepage

License

MIT (license)

Dependencies

flutter, shared_preferences

More

Packages that depend on iws_cache