calorimeter/lib/food_entry_bloc.dart

65 lines
1.5 KiB
Dart
Raw Normal View History

import 'package:flutter_bloc/flutter_bloc.dart';
2024-06-09 12:42:17 +00:00
import 'package:uuid/uuid.dart';
2024-06-09 12:42:17 +00:00
class FoodEntryBloc extends Bloc<FoodEvent, FoodEntryState> {
FoodEntryBloc(super.initialState) {
on<FoodEntryEvent>(addFoodEntryToState);
2024-06-09 12:42:17 +00:00
on<FoodDeletionEvent>(deleteFood);
}
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-06-09 12:42:17 +00:00
class FoodEvent {}
class FoodEntryEvent extends FoodEvent {
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});
}
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;
FoodEntry({
required this.name,
required this.mass,
required this.kcalPerMass,
2024-06-09 12:42:17 +00:00
}) : id = const Uuid().v1();
}