65 lines
1.5 KiB
Dart
65 lines
1.5 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:uuid/uuid.dart';
|
|
|
|
class FoodEntryBloc extends Bloc<FoodEvent, FoodEntryState> {
|
|
FoodEntryBloc(super.initialState) {
|
|
on<FoodEntryEvent>(addFoodEntryToState);
|
|
on<FoodDeletionEvent>(deleteFood);
|
|
}
|
|
|
|
void addFoodEntryToState(FoodEntryEvent event, Emitter<FoodEntryState> emit) {
|
|
FoodEntryState newState = FoodEntryState.from(state);
|
|
newState.addEntry(event.entry);
|
|
emit(newState);
|
|
}
|
|
|
|
void deleteFood(FoodDeletionEvent event, Emitter<FoodEntryState> emit) {
|
|
state.foodEntries.removeWhere((entry) => entry.id == event.entryID);
|
|
emit(FoodEntryState.from(state));
|
|
}
|
|
}
|
|
|
|
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 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();
|
|
}
|