From 8fed846eac9041b2450e22c40efcf6428c3ef3dd Mon Sep 17 00:00:00 2001 From: Felix Kirchner Date: Wed, 30 Apr 2025 17:16:15 +0200 Subject: [PATCH] Implemented LocalStorageService --- lib/utility/local_storage_service.dart | 58 ++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 lib/utility/local_storage_service.dart diff --git a/lib/utility/local_storage_service.dart b/lib/utility/local_storage_service.dart new file mode 100644 index 0000000..ada8492 --- /dev/null +++ b/lib/utility/local_storage_service.dart @@ -0,0 +1,58 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cabo_counter/data/game_session.dart'; +import 'package:cabo_counter/utility/globals.dart'; +import 'package:path_provider/path_provider.dart'; + +class LocalStorageService { + static const String _fileName = 'game_data.json'; + + /// Speichert GameSessions im App-Dokumentenverzeichnis + static Future saveGameSessions() async { + try { + List sessions = Globals.gameList; + final file = await _getLocalFile(); + final jsonList = sessions.map((session) => session.toJson()).toList(); + await file.writeAsString(json.encode(jsonList)); + print('Daten gespeichert'); + } catch (e) { + print('Fehler beim Speichern: $e'); + } + } + + /// Lädt GameSessions aus dem App-Dokumentenverzeichnis + static Future loadGameSessions() async { + print('Versuche, Daten zu laden...'); // FIXME Debug-Ausgabe + try { + final file = await _getLocalFile(); + if (await file.exists()) { + print('Datei existiert'); // FIXME Debug-Ausgabe + final jsonString = await file.readAsString(); + if (jsonString.isNotEmpty) { + print('Datei ist nicht leer'); // FIXME Debug-Ausgabe + final jsonList = json.decode(jsonString) as List; + print('JSON: $jsonList'); // FIXME Debug-Ausgabe + Globals.gameList = + jsonList.map((json) => GameSession.fromJson(json)).toList(); + print('Daten erfolgreich geladen'); + } else { + print('Datei ist leer'); + } + } else { + print('Datei existiert nicht'); + } + } catch (e) { + print('Fehler beim Laden: $e'); + // Bei Fehler eine leere Liste setzen + Globals.gameList = []; + } + } + + static Future _getLocalFile() async { + final directory = await getApplicationDocumentsDirectory(); + final path = '${directory.path}/$_fileName'; + print('Speicherpfad: $path'); // FIXME Debug-Ausgabe + return File(path); + } +}