60 lines
2.0 KiB
Dart
60 lines
2.0 KiB
Dart
// * Shared method for saving entries to text files
|
|
// * Allows users to:
|
|
// * - Select a save directory
|
|
// * - Save entries as JSON files
|
|
// * - Persist the chosen directory for future use
|
|
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:fforte/enums/databases.dart';
|
|
import 'package:fforte/screens/excursion/exceptions/file_dialog_cancelled.dart';
|
|
import 'package:file_picker/file_picker.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// Helper class for saving entries to files
|
|
class SaveFileMethod {
|
|
/// Save an entry to a text file in JSON format
|
|
/// @param place Map containing the entry data
|
|
/// @param id ID of the entry
|
|
/// @param fileNameLocalization Localized prefix for the filename
|
|
/// @param dbType The type of database (place/excursion)
|
|
/// @throws FileDialogCancelled if user cancels directory selection
|
|
static Future<void> saveFile(
|
|
Map<String, String> place,
|
|
int id,
|
|
String fileNameLocalization,
|
|
DatabasesEnum dbType,
|
|
) async {
|
|
try {
|
|
// Let user select save directory
|
|
String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
|
|
|
|
if (selectedDirectory == null) {
|
|
throw FileDialogCancelled();
|
|
}
|
|
|
|
// Save entry as JSON
|
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
|
String jsonPlace = jsonEncode(place);
|
|
|
|
// Remember selected directory for future use
|
|
await prefs.setString('saveDir', selectedDirectory);
|
|
|
|
// Create file with format: prefix-id-identifier.txt
|
|
// For places: identifier = CID
|
|
// For excursions: identifier = date
|
|
File file = File(
|
|
'$selectedDirectory/$fileNameLocalization-$id-${dbType == DatabasesEnum.place ? place["CID"] : place["Datum"]!.split(" ").first}.txt',
|
|
);
|
|
|
|
// Write JSON data to file
|
|
await file.writeAsString(jsonPlace);
|
|
} catch (e) {
|
|
debugPrint(e.toString());
|
|
rethrow; // Re-throw to allow proper error handling by caller
|
|
}
|
|
}
|
|
}
|