stashbox 0.0.1
stashbox: ^0.0.1 copied to clipboard
A lightweight, persistent JSON storage solution for Dart and Flutter applications
StashBox #
A lightweight, persistent JSON storage solution for Dart and Flutter applications
Features #
- Persistent JSON Storage: Store and retrieve data in JSON format
- Transaction Support: Group operations with commit/rollback capabilities
- Caching: Configurable in-memory caching for improved performance
- Type Safety: Get typed values with default fallbacks
- Object Serialization: Helpers for storing complex objects
- Batch Operations: Perform multiple operations efficiently
- Error Handling: Specialized exceptions for better error reporting
- File Integrity: Automatic backup creation for corrupted files
Getting Started #
Add the package to your pubspec.yaml:
dependencies:
stashbox: ^0.0.1
Usage #
import 'package:stashbox/stashbox.dart';
void main() async {
// Create a store with a file path
final store = StashBox('data.json');
// Basic operations
await basicOperations(store);
// Type safety examples
await typeHandling(store);
// Working with complex objects
await objectOperations(store);
// Transaction examples
await transactionExample(store);
// Performance optimization with caching
cachingExamples(store);
// Batch operations for efficiency
await batchOperations(store);
}
Future<void> basicOperations(StashBox store) async {
// Store simple values
await store.set('username', 'john_doe');
await store.set('is_admin', false);
await store.set('last_login', DateTime.now().toIso8601String());
await store.set('preferences', {'theme': 'dark', 'notifications': true});
// Retrieve values
final username = await store.get<String>('username');
print('Username: $username');
// Check if key exists
if (await store.has('username')) {
print('Username exists!');
}
// Remove a key
await store.remove('temporary_data');
// Get all data
final allData = await store.getAll();
print('All data: $allData');
}
Future<void> typeHandling(StashBox store) async {
// Type-safe retrieval with default values
final count = await store.getTyped<int>('count', 0);
print('Count (with default): $count');
// Required values that throw if missing
try {
final requiredValue = await store.getRequired<String>('required_key');
print('Required value: $requiredValue');
} catch (e) {
print('Error getting required value: $e');
}
}
Future<void> objectOperations(StashBox store) async {
// Define a simple user class
class User {
final String name;
final int age;
User(this.name, this.age);
Map<String, dynamic> toJson() => {'name': name, 'age': age};
static User fromJson(Map<String, dynamic> json) {
return User(json['name'], json['age']);
}
}
// Store a single object
final user = User('Alice', 28);
await store.setObject('current_user', user, (u) => u.toJson());
// Retrieve the object
final retrievedUser = await store.getObject<User>(
'current_user',
User.fromJson
);
print('Retrieved user: ${retrievedUser?.name}, ${retrievedUser?.age}');
// Store a list of objects
final users = [
User('Bob', 32),
User('Carol', 27),
User('Dave', 35)
];
await store.setObjectList('users', users, (u) => u.toJson());
// Retrieve the list
final retrievedUsers = await store.getObjectList<User>(
'users',
User.fromJson
);
print('Retrieved ${retrievedUsers?.length} users');
}
Future<void> transactionExample(StashBox store) async {
// Using the transaction helper method
await store.transaction(() async {
await store.set('counter', 42);
await store.set('status', 'active');
// This would be rolled back if any error occurs
// throw Exception('Oops!');
});
// Manual transaction handling
await store.beginTransaction();
try {
await store.set('user_id', 1001);
await store.set('logged_in', true);
await store.commitTransaction();
print('Transaction committed successfully');
} catch (e) {
store.rollbackTransaction();
print('Transaction rolled back: $e');
rethrow;
}
}
void cachingExamples(StashBox store) {
// Enable caching with custom size
store.configureCaching(enabled: true, maxSize: 500);
// Invalidate specific keys in cache
store.invalidateCache(['user', 'settings']);
// Invalidate entire cache
store.invalidateCache();
}
Future<void> batchOperations(StashBox store) async {
// Perform multiple operations efficiently
await store.batch((batchStore) async {
await batchStore.set('item1', 'value1');
await batchStore.set('item2', 'value2');
await batchStore.set('item3', 'value3');
return true;
});
// Update multiple values at once
await store.update({
'setting1': 'value1',
'setting2': 'value2',
'setting3': 'value3',
});
}