loadData method
Loads data from storage.
key is the unique identifier for the data.
If decompress is true, the data will be decompressed after loading.
If decrypt is true, the data will be decrypted after loading.
Implementation
Future<Map<String, dynamic>?> loadData(String key,
{bool decompress = false, bool decrypt = false}) async {
try {
debugPrint('Loading data for key: $key');
final storedData = await _box.get(key);
if (storedData == null) {
debugPrint('No data found for key: $key');
return null;
}
String processedData = storedData['data'];
if (decrypt && storedData['encrypted']) {
if (_encrypter == null) {
throw Exception(
'Encryption key not set. Call initialize with an encryption key before using decryption.');
}
processedData = _decryptString(processedData);
debugPrint('Data decrypted for key: $key');
}
if (decompress && storedData['compressed']) {
processedData = _decompressString(processedData);
debugPrint('Data decompressed for key: $key');
}
final decodedData = json.decode(processedData);
debugPrint('Data decoded for key: $key');
debugPrint('Data version: ${storedData['version']}');
debugPrint('Data hash: ${storedData['hash']}');
debugPrint('Data decompressed : $processedData');
debugPrint('Data decoded : $decodedData');
// // Convert Map<dynamic, dynamic> to Map<String, dynamic>
// final Map<String, dynamic> typedData =
// _convertToStringDynamicMap(decodedData);
final String hash = _calculateHash(json.encode(decodedData));
if (hash != storedData['hash']) {
throw Exception('Data integrity check failed for key $key');
}
debugPrint('Data loaded successfully for key: $key');
return decodedData;
} catch (e) {
debugPrint('Failed to load data for key $key: $e');
return null;
}
}