Marco
b83f547f6b
Now, an on-the-fly food lookup is created from existing entries on startup. Those entries are used to make suggestions when the user is typing to enter new food entries.
103 lines
2.5 KiB
Dart
103 lines
2.5 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:calodiary/storage/storage.dart';
|
|
import 'package:uuid/uuid.dart';
|
|
|
|
class FoodEntryBloc extends Bloc<FoodEvent, FoodEntryState> {
|
|
final FoodEntryState initialState;
|
|
final FoodStorage storage;
|
|
final DateTime forDate;
|
|
|
|
FoodEntryBloc(
|
|
{required this.initialState,
|
|
required this.forDate,
|
|
required this.storage})
|
|
: super(initialState) {
|
|
on<FoodEntryEvent>(handleFoodEntryEvent);
|
|
on<FoodDeletionEvent>(deleteFood);
|
|
on<PageChangedEvent>(updateEntries);
|
|
}
|
|
|
|
void handleFoodEntryEvent(
|
|
FoodEntryEvent event, Emitter<FoodEntryState> emit) async {
|
|
FoodEntryState newState = FoodEntryState.from(state);
|
|
newState.addEntry(event.entry);
|
|
|
|
await storage.writeEntriesForDate(forDate, newState.foodEntries);
|
|
storage.addFoodEntryToLookupDatabase(event.entry);
|
|
|
|
emit(newState);
|
|
}
|
|
|
|
void deleteFood(FoodDeletionEvent event, Emitter<FoodEntryState> emit) async {
|
|
state.foodEntries.removeWhere((entry) => entry.id == event.entryID);
|
|
|
|
await storage.writeEntriesForDate(forDate, state.foodEntries);
|
|
|
|
emit(FoodEntryState.from(state));
|
|
}
|
|
|
|
void updateEntries(
|
|
PageChangedEvent event, Emitter<FoodEntryState> emit) async {
|
|
var entries = await storage.getEntriesForDate(event.changedToDate);
|
|
var newState = FoodEntryState(foodEntries: entries);
|
|
emit(newState);
|
|
}
|
|
}
|
|
|
|
class FoodEvent {}
|
|
|
|
class FoodEntryEvent extends FoodEvent {
|
|
final FoodEntry entry;
|
|
|
|
FoodEntryEvent({required this.entry});
|
|
}
|
|
|
|
class FoodDeletionEvent extends FoodEvent {
|
|
final String entryID;
|
|
|
|
FoodDeletionEvent({required this.entryID});
|
|
}
|
|
|
|
class PageChangedEvent extends FoodEvent {
|
|
final DateTime changedToDate;
|
|
|
|
PageChangedEvent({required this.changedToDate});
|
|
}
|
|
|
|
class FoodEntryState {
|
|
final List<FoodEntry> foodEntries;
|
|
|
|
FoodEntryState({required this.foodEntries});
|
|
|
|
factory FoodEntryState.init() {
|
|
return FoodEntryState(foodEntries: []);
|
|
}
|
|
|
|
static from(FoodEntryState state) {
|
|
List<FoodEntry> newList = List.from(state.foodEntries);
|
|
return FoodEntryState(foodEntries: newList);
|
|
}
|
|
|
|
void addEntry(FoodEntry entry) {
|
|
foodEntries.add(entry);
|
|
}
|
|
}
|
|
|
|
class FoodEntry {
|
|
final String name;
|
|
final double mass;
|
|
final double kcalPerMass;
|
|
final String id;
|
|
|
|
FoodEntry({
|
|
required this.name,
|
|
required this.mass,
|
|
required this.kcalPerMass,
|
|
}) : id = const Uuid().v1();
|
|
|
|
@override
|
|
String toString() {
|
|
return '$id,$name,$mass,$kcalPerMass';
|
|
}
|
|
}
|