nosql_cache_manager 1.0.0
nosql_cache_manager: ^1.0.0 copied to clipboard
A powerful Flutter cache manager with automatic expiration, batch operations, and comprehensive cache management using Sembast NoSQL database.
import 'package:flutter/material.dart';
import 'package:nosql_cache_manager/nosql_cache_manager.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'NoSQL Cache Manager Example',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true,
),
home: const CacheManagerDemo(),
);
}
}
class CacheManagerDemo extends StatefulWidget {
const CacheManagerDemo({super.key});
@override
State<CacheManagerDemo> createState() => _CacheManagerDemoState();
}
class _CacheManagerDemoState extends State<CacheManagerDemo> {
final CacheManager _cacheManager = CacheManager();
String _output = 'Welcome to NoSQL Cache Manager Demo!';
int _cacheSize = 0;
List<String> _cacheKeys = [];
@override
void initState() {
super.initState();
_initializeCache();
}
@override
void dispose() {
_cacheManager.close();
super.dispose();
}
Future<void> _initializeCache() async {
await _cacheManager.init();
await _updateCacheStats();
}
Future<void> _updateCacheStats() async {
final size = await _cacheManager.getCacheSize();
final keys = await _cacheManager.getAllKeys();
if (mounted) {
setState(() {
_cacheSize = size;
_cacheKeys = keys;
});
}
}
void _showMessage(String message) {
if (mounted) {
setState(() {
_output = message;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
}
}
Future<void> _basicOperationsDemo() async {
try {
// Store different types of data
await _cacheManager.setCache('string_data', 'Hello, World!');
await _cacheManager.setCache('number_data', 42);
await _cacheManager.setCache('list_data', [1, 2, 3, 'four', true]);
await _cacheManager.setCache('map_data', {
'user': {'name': 'John', 'age': 30},
'preferences': ['dark_mode', 'notifications']
});
// Retrieve and display
final stringData = await _cacheManager.getCache('string_data');
final mapData = await _cacheManager.getCache('map_data');
_showMessage('Basic operations completed!\nString: $stringData\nUser: ${mapData['user']['name']}');
await _updateCacheStats();
} catch (e) {
_showMessage('Error in basic operations: $e');
}
}
Future<void> _batchOperationsDemo() async {
try {
// Batch set
await _cacheManager.setBatch({
'user_1': {'name': 'Alice', 'role': 'admin'},
'user_2': {'name': 'Bob', 'role': 'user'},
'user_3': {'name': 'Charlie', 'role': 'moderator'},
}, duration: const Duration(minutes: 10));
// Batch get
final results = await _cacheManager.getBatch(['user_1', 'user_2', 'user_4']);
_showMessage('Batch operations completed!\nUser 1: ${results['user_1']?['name']}\nUser 2: ${results['user_2']?['name']}\nUser 4: ${results['user_4'] ?? 'Not found'}');
await _updateCacheStats();
} catch (e) {
_showMessage('Error in batch operations: $e');
}
}
Future<void> _expirationDemo() async {
try {
// Set data with short expiration
await _cacheManager.setCache(
'temp_data',
'This will expire soon!',
duration: const Duration(seconds: 3)
);
_showMessage('Temporary data cached for 3 seconds...');
// Wait and check
await Future.delayed(const Duration(seconds: 4));
final expiredData = await _cacheManager.getCache('temp_data');
_showMessage('After 4 seconds: ${expiredData ?? 'Data expired (as expected)'}');
await _updateCacheStats();
} catch (e) {
_showMessage('Error in expiration demo: $e');
}
}
Future<void> _cleanupDemo() async {
try {
// Add some data with short expiration
await _cacheManager.setBatch({
'expire_1': 'Will expire',
'expire_2': 'Will also expire',
'keep_me': 'Will stay',
});
// Set different expiration times
await _cacheManager.setCache('expire_1', 'Will expire', duration: const Duration(milliseconds: 100));
await _cacheManager.setCache('expire_2', 'Will also expire', duration: const Duration(milliseconds: 100));
await _cacheManager.setCache('keep_me', 'Will stay', duration: const Duration(hours: 1));
await Future.delayed(const Duration(milliseconds: 200));
final cleanedCount = await _cacheManager.cleanExpired();
_showMessage('Cleanup completed! Removed $cleanedCount expired entries');
await _updateCacheStats();
} catch (e) {
_showMessage('Error in cleanup demo: $e');
}
}
Future<void> _clearAllCache() async {
try {
await _cacheManager.clearAllCache();
_showMessage('All cache cleared!');
await _updateCacheStats();
} catch (e) {
_showMessage('Error clearing cache: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('NoSQL Cache Manager Demo'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Cache Statistics Card
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Cache Statistics',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text('Size: $_cacheSize entries'),
Text('Keys: ${_cacheKeys.join(', ')}'),
],
),
),
),
const SizedBox(height: 16),
// Output Display
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Output',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(8),
),
child: Text(
_output,
style: const TextStyle(fontFamily: 'monospace'),
),
),
],
),
),
),
const SizedBox(height: 16),
// Demo Buttons
Text(
'Demos',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: _basicOperationsDemo,
icon: const Icon(Icons.storage),
label: const Text('Basic Operations'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: _batchOperationsDemo,
icon: const Icon(Icons.batch_prediction),
label: const Text('Batch Operations'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: _expirationDemo,
icon: const Icon(Icons.timer),
label: const Text('Expiration Demo'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: _cleanupDemo,
icon: const Icon(Icons.cleaning_services),
label: const Text('Cleanup Demo'),
),
const SizedBox(height: 16),
// Utility Buttons
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: _updateCacheStats,
icon: const Icon(Icons.refresh),
label: const Text('Refresh Stats'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: _clearAllCache,
icon: const Icon(Icons.clear_all),
label: const Text('Clear All'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
),
),
],
),
],
),
),
);
}
}