saveDecryptedContent function
Saves decrypted content to a file, handling different file formats appropriately.
Attempts to save as JSON if possible, falls back to binary or text based on file type.
Implementation
Future<void> saveDecryptedContent(
String decryptedContent, String saveFilePath) async {
final file = File(saveFilePath);
// Ensure the parent directory exists.
await file.parent.create(recursive: true);
try {
// Try to parse and save as formatted JSON first.
try {
final jsonData = jsonDecode(decryptedContent);
await file
.writeAsString(const JsonEncoder.withIndent(' ').convert(jsonData));
return;
} catch (jsonError) {
debugPrint('JSON parsing failed: $jsonError');
debugPrint('Raw decrypted content: $decryptedContent');
// If not JSON, handle as binary or text.
if (isTextFile(saveFilePath)) {
await file.writeAsString(decryptedContent);
} else {
// For binary files, try base64 decode.
try {
final bytes = base64Decode(decryptedContent);
await file.writeAsBytes(bytes);
} catch (base64Error) {
debugPrint('Base64 decode failed: $base64Error');
await file.writeAsString(decryptedContent);
}
}
}
} catch (e) {
throw Exception('Failed to save file: ${e.toString()}');
}
}