stashbox 0.0.4
stashbox: ^0.0.4 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.4
Usage #
import 'package:stashbox/stashbox.dart';
// Create a StashBox with a file path
final store = StashBox('data/mystore.json');
// Enable caching for better performance
store.configureCaching(enabled: true, maxSize: 100);
////// Simple Operations
await store.set('username', 'spicy_katsu');
await store.set('age', 25);
await store.set('isActive', true);
// Retrieve values
final username = await store.get<String>('username');
final age = await store.getTyped<int>('age', 0); // With default value
final isActive = await store.getRequired<bool>('isActive'); // Throws if not found
// Check if a key exists
if (await store.has('username')) {
print('Username exists!');
}
// Remove a value
await store.remove('age');
// Clear all data
await store.clear();
// Create a backup
final backupPath = await store.backup();
print('Backup created at: $backupPath');
// Restore from backup
final backupFile = File(backupPath!);
final success = await store.restore(backupFile);
////// Working with Objects
class User {
final String name;
final int age;
User(this.name, this.age);
// Convert User to JSON
Map<String, dynamic> toJson() => {
'name': name,
'age': age,
};
// Create User from JSON
static User fromJson(Map<String, dynamic> json) =>
User(json['name'], json['age']);
}
// Store an object
final user = User('Alice', 30);
await store.setObject('user1', user, (u) => u.toJson());
// Retrieve an object
final retrievedUser = await store.getObject('user1', User.fromJson);
// Store a list of objects
final users = [User('Alice', 30), User('Bob', 25)];
await store.setObjectList('users', users, (u) => u.toJson());
// Retrieve a list of objects
final retrievedUsers = await store.getObjectList('users', User.fromJson);
////// Transactions
final result = await store.transaction(() async {
await store.set('counter', 1);
await store.set('message', 'Transaction in progress');
return true;
});
// Manual transaction control
await store.beginTransaction();
try {
await store.set('key1', 'value1');
await store.set('key2', 'value2');
await store.commitTransaction();
} catch (e) {
store.rollbackTransaction();
rethrow;
}