2024-05-29 22:58:26 +00:00
|
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
2024-06-09 12:42:17 +00:00
|
|
|
import 'package:uuid/uuid.dart';
|
2024-05-29 22:58:26 +00:00
|
|
|
|
2024-06-09 12:42:17 +00:00
|
|
|
class FoodEntryBloc extends Bloc<FoodEvent, FoodEntryState> {
|
2024-05-29 22:58:26 +00:00
|
|
|
FoodEntryBloc(super.initialState) {
|
|
|
|
on<FoodEntryEvent>(addFoodEntryToState);
|
2024-06-09 12:42:17 +00:00
|
|
|
on<FoodDeletionEvent>(deleteFood);
|
2024-05-29 22:58:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void addFoodEntryToState(FoodEntryEvent event, Emitter<FoodEntryState> emit) {
|
|
|
|
FoodEntryState newState = FoodEntryState.from(state);
|
|
|
|
newState.addEntry(event.entry);
|
|
|
|
emit(newState);
|
|
|
|
}
|
2024-06-09 12:42:17 +00:00
|
|
|
|
|
|
|
void deleteFood(FoodDeletionEvent event, Emitter<FoodEntryState> emit) {
|
|
|
|
state.foodEntries.removeWhere((entry) => entry.id == event.entryID);
|
|
|
|
emit(FoodEntryState.from(state));
|
|
|
|
}
|
2024-05-29 22:58:26 +00:00
|
|
|
}
|
|
|
|
|
2024-06-09 12:42:17 +00:00
|
|
|
class FoodEvent {}
|
|
|
|
|
|
|
|
class FoodEntryEvent extends FoodEvent {
|
2024-05-29 22:58:26 +00:00
|
|
|
final FoodEntry entry;
|
|
|
|
FoodEntryEvent({required this.entry});
|
|
|
|
}
|
|
|
|
|
2024-06-09 12:42:17 +00:00
|
|
|
class FoodDeletionEvent extends FoodEvent {
|
|
|
|
final String entryID;
|
|
|
|
FoodDeletionEvent({required this.entryID});
|
|
|
|
}
|
|
|
|
|
2024-05-29 22:58:26 +00:00
|
|
|
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;
|
2024-06-09 12:42:17 +00:00
|
|
|
final String id;
|
2024-05-29 22:58:26 +00:00
|
|
|
|
|
|
|
FoodEntry({
|
|
|
|
required this.name,
|
|
|
|
required this.mass,
|
|
|
|
required this.kcalPerMass,
|
2024-06-09 12:42:17 +00:00
|
|
|
}) : id = const Uuid().v1();
|
2024-05-29 22:58:26 +00:00
|
|
|
}
|