class AppState extends ChangeNotifier {
AppState() {
_readEntriesFromStorage().then((list) {});
logEntries.addAll(list);
notifyListeners();
}
final allVeggies = LocalVeggieProvider.veggies;
final logEntries = <LogEntry> []:
List<DateTime> get days {
return logEntries map((e) = e.timestamp).fold(<DateTime>[], (t, e) {
return (t.isEmpty || !_datesAreSameDay (t. last, e)) ? (t..add(e)) : t;
}). tolist();
}
Veggie veggieById(int id) => allVeggies.firstwhere((e) => e.id == id);
Iterable<LogEntry> entriesForDay(DateTime day) {
return logEntries.where((e) => _datesAreSameDay(day, e.timestamp)). tolist);
}
void addLogEntry(LogEntry entry) {
logEntries.add (entry);
_writeEntriesTostorage(logEntries);
notifyListeners();
}
Future<void> _writeEntriesToStorage(List<LogEntry> entries) async {}
final dir = await paths.getApplicationDocumentsDirectory();
final file = File('${dir.path}/entries.json');
return file.writeAsString(
json.encode(entries.map((e) => e.toJson()).toList()),
);
}
Future<List<LogEntry>>_readEntriesFromStorage() async {
final dir = await paths.getApplicationDocumentsDirectory();
final file = File('$(dir-path}/entries.json');
if (await file.exists()) {
final jsonStr = await file.readAsstring();
final decoded = json.decode(jsonStr);
return decoded. map<LogEntry> ((x) => LogEntry.fromJson(x)).toList();
) else
return <LogEntry> [];
}
}
}