60 lines
1.4 KiB
Dart
60 lines
1.4 KiB
Dart
|
import 'dart:io';
|
||
|
|
||
|
import 'package:kalodings/food_entry_bloc.dart';
|
||
|
import 'package:path_provider/path_provider.dart';
|
||
|
|
||
|
class FoodStorage {
|
||
|
late String path;
|
||
|
FoodStorage._create();
|
||
|
|
||
|
static Future<FoodStorage> create() async {
|
||
|
var storage = FoodStorage._create();
|
||
|
var directory = await getApplicationCacheDirectory();
|
||
|
storage.path = directory.path;
|
||
|
|
||
|
return storage;
|
||
|
}
|
||
|
|
||
|
Future<List<FoodEntry>> getEntriesForDate(DateTime date) async {
|
||
|
List<FoodEntry> entries = [];
|
||
|
var filePath = '$path/${date.year}/${date.month}/${date.day}';
|
||
|
|
||
|
var file = File(filePath);
|
||
|
var exists = await file.exists();
|
||
|
|
||
|
if (!exists) return [];
|
||
|
|
||
|
var lines = await file.readAsLines();
|
||
|
|
||
|
for (var line in lines) {
|
||
|
var fields = line.split(',');
|
||
|
var entry = FoodEntry(
|
||
|
name: fields[1],
|
||
|
mass: double.parse(fields[2]),
|
||
|
kcalPerMass: double.parse(fields[3]));
|
||
|
entries.add(entry);
|
||
|
}
|
||
|
|
||
|
return entries;
|
||
|
}
|
||
|
|
||
|
Future<void> writeEntriesForDate(
|
||
|
DateTime date, List<FoodEntry> foodEntries) async {
|
||
|
var filePath = '$path/${date.year}/${date.month}/${date.day}';
|
||
|
var file = File(filePath);
|
||
|
|
||
|
var exists = await file.exists();
|
||
|
|
||
|
if (!exists) {
|
||
|
await file.create(recursive: true);
|
||
|
}
|
||
|
|
||
|
String fullString = '';
|
||
|
for (var entry in foodEntries) {
|
||
|
fullString += '${entry.toString()}\n';
|
||
|
}
|
||
|
|
||
|
await file.writeAsString(fullString);
|
||
|
}
|
||
|
}
|