Roadbound-BRR/lib/services/storage_service.dart

36 lines
991 B
Dart

import "dart:convert";
import "package:flutter/foundation.dart";
import "package:hive_flutter/hive_flutter.dart";
import "../models/brr_state.dart";
class StorageService {
static const _boxName = "brr_box";
static const _stateKey = "brr_state";
Future<Box<String>> _openBox() => Hive.openBox<String>(_boxName);
Future<void> saveState(BRRState state) async {
final box = await _openBox();
await box.put(_stateKey, jsonEncode(state.toJson()));
}
Future<BRRState?> loadState() async {
final box = await _openBox();
final jsonString = box.get(_stateKey);
if (jsonString == null) return null;
try {
return BRRState.fromJson(jsonDecode(jsonString) as Map<String, dynamic>);
} catch (e, stackTrace) {
debugPrint("[StorageService] loadState failed: $e");
debugPrintStack(stackTrace: stackTrace);
return null;
}
}
Future<void> clearState() async {
final box = await _openBox();
await box.delete(_stateKey);
}
}