Compare commits

..

No commits in common. "master" and "swipeable-pages" have entirely different histories.

5 changed files with 140 additions and 204 deletions

View File

@ -4,96 +4,61 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:calorimeter/storage/storage.dart';
import 'package:uuid/uuid.dart';
class FoodEntryBloc extends Bloc<FoodEvent, GlobalEntryState> {
final GlobalEntryState initialState;
class FoodEntryBloc extends Bloc<FoodEvent, PageState> {
final PageState initialState;
final FoodStorage storage;
final DateTime forDate;
FoodEntryBloc({required this.initialState, required this.storage})
FoodEntryBloc(
{required this.initialState,
required this.forDate,
required this.storage})
: super(initialState) {
on<PageBeingInitialized>(handlePageBeingInitialized);
on<FoodEntryEvent>(handleFoodEntryEvent);
on<FoodChangedEvent>(handleFoodChangedEvent);
on<FoodDeletionEvent>(handleDeleteFoodEvent);
on<BarcodeScanned>(handleBarcodeScannedEvent);
on<FoodEntryTapped>(handleFoodEntryTapped);
}
void handlePageBeingInitialized(
PageBeingInitialized event, Emitter<GlobalEntryState> emit) async {
var newList = await storage.getEntriesForDate(event.forDate);
state.foodEntries.addAll({event.forDate: newList});
emit(GlobalEntryState(foodEntries: state.foodEntries));
}
void handleFoodEntryEvent(
FoodEntryEvent event, Emitter<GlobalEntryState> emit) async {
var entriesForDate = state.foodEntries[event.forDate];
entriesForDate ??= [];
FoodEntryEvent event, Emitter<PageState> emit) async {
PageState newState = PageState.from(state);
newState.addEntry(event.entry);
entriesForDate.add(event.entry);
await storage.writeEntriesForDate(event.forDate, entriesForDate);
await storage.writeEntriesForDate(forDate, newState.foodEntries);
storage.addFoodEntryToLookupDatabase(event.entry);
// this is just checking if writing to the database worked
// can be optimized out by just emitting newState
var newList = await storage.getEntriesForDate(event.forDate);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: newList});
emit(GlobalEntryState(foodEntries: newFoodEntries));
emit(newState);
}
void handleFoodChangedEvent(
FoodChangedEvent event, Emitter<GlobalEntryState> emit) async {
var entriesForDate = state.foodEntries[event.forDate];
if (entriesForDate == null) return;
var index = entriesForDate.indexWhere((entry) {
FoodChangedEvent event, Emitter<PageState> emit) async {
var entries = state.foodEntries;
var index = entries.indexWhere((entry) {
return entry.id == event.newEntry.id;
});
entriesForDate.removeAt(index);
entriesForDate.insert(index, event.newEntry);
entries.removeAt(index);
entries.insert(index, event.newEntry);
await storage.writeEntriesForDate(event.forDate, entriesForDate);
await storage.writeEntriesForDate(forDate, entries);
storage.addFoodEntryToLookupDatabase(event.newEntry);
// this is just checking if writing to the database worked
// can be optimized out by just emitting newState
var newList = await storage.getEntriesForDate(event.forDate);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: newList});
emit(GlobalEntryState(foodEntries: newFoodEntries));
emit(PageState(foodEntries: entries));
}
void handleDeleteFoodEvent(
FoodDeletionEvent event, Emitter<GlobalEntryState> emit) async {
var entriesForDate = state.foodEntries[event.forDate];
if (entriesForDate == null) return;
FoodDeletionEvent event, Emitter<PageState> emit) async {
state.foodEntries.removeWhere((entry) => entry.id == event.entryID);
entriesForDate.removeWhere((entry) => entry.id == event.entryID);
await storage.writeEntriesForDate(forDate, state.foodEntries);
await storage.writeEntriesForDate(event.forDate, entriesForDate);
// this is just checking if writing to the database worked
// can be optimized out by just emitting newState
var newList = await storage.getEntriesForDate(event.forDate);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: newList});
emit(GlobalEntryState(foodEntries: newFoodEntries));
emit(PageState.from(state));
}
void handleBarcodeScannedEvent(
BarcodeScanned event, Emitter<GlobalEntryState> emit) async {
var entriesForDate = state.foodEntries[event.forDate];
if (entriesForDate == null) return;
BarcodeScanned event, Emitter<PageState> emit) async {
var client = FoodFactLookupClient();
var scanResult = await event.scanResultFuture;
@ -101,13 +66,14 @@ class FoodEntryBloc extends Bloc<FoodEvent, GlobalEntryState> {
return;
}
if (scanResult.type == ResultType.Error) {
emit(GlobalEntryState(
emit(PageState(
foodEntries: state.foodEntries,
errorString: "Fehler beim Scannen des Barcodes"));
return;
}
var responseFuture = client.retrieveFoodInfo(scanResult.rawContent);
List<FoodEntryState> newList = List.from(state.foodEntries);
var newEntryWaiting = FoodEntryState(
kcalPer100: 0,
name: "",
@ -115,13 +81,11 @@ class FoodEntryBloc extends Bloc<FoodEvent, GlobalEntryState> {
waitingForNetwork: true,
isSelected: false,
);
entriesForDate.add(newEntryWaiting);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: entriesForDate});
emit(GlobalEntryState(foodEntries: newFoodEntries));
newList.add(newEntryWaiting);
emit(PageState(foodEntries: newList));
await responseFuture.then((response) async {
var index = entriesForDate
var index = newList
.indexWhere((entryState) => entryState.id == newEntryWaiting.id);
// element not found (was deleted previously)
@ -130,23 +94,25 @@ class FoodEntryBloc extends Bloc<FoodEvent, GlobalEntryState> {
}
if (response.status == FoodFactResponseStatus.barcodeNotFound) {
entriesForDate.removeWhere((entry) => entry.id == newEntryWaiting.id);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: entriesForDate});
List<FoodEntryState> listWithEntryRemoved =
List.from(state.foodEntries);
listWithEntryRemoved
.removeWhere((entry) => entry.id == newEntryWaiting.id);
emit(GlobalEntryState(
foodEntries: newFoodEntries,
emit(PageState(
foodEntries: listWithEntryRemoved,
errorString: "Barcode konnte nicht gefunden werden."));
return;
}
if (response.status ==
FoodFactResponseStatus.foodFactServerNotReachable) {
entriesForDate.removeWhere((entry) => entry.id == newEntryWaiting.id);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: entriesForDate});
List<FoodEntryState> listWithEntryRemoved =
List.from(state.foodEntries);
listWithEntryRemoved
.removeWhere((entry) => entry.id == newEntryWaiting.id);
emit(GlobalEntryState(
foodEntries: newFoodEntries,
emit(PageState(
foodEntries: listWithEntryRemoved,
errorString: "OpenFoodFacts-Server konnte nicht erreicht werden."));
return;
}
@ -159,114 +125,91 @@ class FoodEntryBloc extends Bloc<FoodEvent, GlobalEntryState> {
isSelected: false,
);
entriesForDate.removeAt(index);
entriesForDate.insert(index, newEntryFinishedWaiting);
newList.removeAt(index);
newList.insert(index, newEntryFinishedWaiting);
await storage.writeEntriesForDate(event.forDate, entriesForDate);
await storage.writeEntriesForDate(forDate, newList);
storage.addFoodEntryToLookupDatabase(newEntryFinishedWaiting);
var entriesFromStorage = await storage.getEntriesForDate(event.forDate);
var newFoodEntries = state.foodEntries;
newFoodEntries.addAll({event.forDate: entriesFromStorage});
emit(GlobalEntryState(foodEntries: newFoodEntries));
emit(PageState(foodEntries: newList));
});
}
void handleFoodEntryTapped(
FoodEntryTapped event, Emitter<GlobalEntryState> emit) async {
var entriesForDate = state.foodEntries[event.forDate];
if (entriesForDate == null) return;
FoodEntryTapped event, Emitter<PageState> emit) async {
var oldStateOfTappedEntry = event.entry.isSelected;
for (var entry in entriesForDate) {
for (var entry in state.foodEntries) {
entry.isSelected = false;
}
var selectedEntry = entriesForDate.firstWhere((entry) {
var selectedEntry = state.foodEntries.firstWhere((entry) {
return entry.id == event.entry.id;
});
selectedEntry.isSelected = !oldStateOfTappedEntry;
emit(GlobalEntryState(foodEntries: state.foodEntries));
emit(PageState(foodEntries: state.foodEntries));
}
}
class FoodEvent {
final DateTime forDate;
FoodEvent({required this.forDate});
}
class PageBeingInitialized extends FoodEvent {
PageBeingInitialized({required super.forDate});
}
class FoodEvent {}
class FoodEntryEvent extends FoodEvent {
final FoodEntryState entry;
FoodEntryEvent({required this.entry, required super.forDate});
FoodEntryEvent({required this.entry});
}
class FoodChangedEvent extends FoodEvent {
final FoodEntryState newEntry;
FoodChangedEvent({required this.newEntry, required super.forDate});
FoodChangedEvent({required this.newEntry});
}
class FoodDeletionEvent extends FoodEvent {
final String entryID;
FoodDeletionEvent({required this.entryID, required super.forDate});
FoodDeletionEvent({required this.entryID});
}
class BarcodeScanned extends FoodEvent {
final Future<ScanResult> scanResultFuture;
BarcodeScanned({required this.scanResultFuture, required super.forDate});
BarcodeScanned({required this.scanResultFuture});
}
class FoodEntryTapped extends FoodEvent {
final FoodEntryState entry;
FoodEntryTapped({required this.entry, required super.forDate});
FoodEntryTapped({required this.entry});
}
/// This is the state for one date/page
class GlobalEntryState {
final Map<DateTime, List<FoodEntryState>> foodEntries;
class PageState {
final List<FoodEntryState> foodEntries;
final String? errorString;
GlobalEntryState({required this.foodEntries, this.errorString});
PageState({required this.foodEntries, this.errorString});
factory GlobalEntryState.init() {
return GlobalEntryState(foodEntries: {});
factory PageState.init() {
return PageState(foodEntries: []);
}
static from(GlobalEntryState state) {
return GlobalEntryState(foodEntries: state.foodEntries);
static from(PageState state) {
return PageState(foodEntries: state.foodEntries);
}
bool addEntry(FoodEntryState entry, DateTime date) {
var list = foodEntries[date];
if (list == null) {
return false;
}
list.add(entry);
return true;
void addEntry(FoodEntryState entry) {
foodEntries.add(entry);
}
}
class FoodEntryState {
final String id;
final String name;
final int mass;
final int kcalPer100;
final String id;
final bool waitingForNetwork;
bool isSelected;

View File

@ -1,4 +1,3 @@
import 'package:calorimeter/food_entry/food_entry_bloc.dart';
import 'package:calorimeter/perdate/perdate_pageview.dart';
import 'package:calorimeter/storage/storage.dart';
import 'package:calorimeter/utils/settings_bloc.dart';
@ -8,9 +7,6 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:go_router/go_router.dart';
List<FoodEntryState> entriesForToday = [];
DateTime timeNow = DateTime.now();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
@ -18,16 +14,6 @@ void main() async {
var storage = await FoodStorage.create();
await storage.buildFoodLookupDatabase();
timeNow = DateTime.now().copyWith(
hour: 0,
isUtc: true,
minute: 0,
second: 0,
millisecond: 0,
microsecond: 0);
entriesForToday = await storage.getEntriesForDate(timeNow);
var kcalLimit = await storage.readLimit();
var brightness = await storage.readBrightness();
@ -56,13 +42,6 @@ class MainApp extends StatelessWidget {
return SafeArea(
child: MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => FoodEntryBloc(
storage: storage,
initialState:
GlobalEntryState(foodEntries: {timeNow: entriesForToday}),
),
),
BlocProvider(
create: (context) => SettingsDataBloc(
SettingsState(kcalLimit: kcalLimit),

View File

@ -6,11 +6,9 @@ import 'package:flutter_bloc/flutter_bloc.dart';
class FoodEntryList extends StatelessWidget {
final List<FoodEntryState> entries;
final DateTime date;
const FoodEntryList({
required this.entries,
required this.date,
super.key,
});
@ -27,7 +25,7 @@ class FoodEntryList extends StatelessWidget {
onAdd: (context, entry) {
context
.read<FoodEntryBloc>()
.add(FoodEntryEvent(entry: entry, forDate: date));
.add(FoodEntryEvent(entry: entry));
},
),
const SizedBox(height: 75),
@ -42,19 +40,19 @@ class FoodEntryList extends StatelessWidget {
key: ValueKey(entries[entryIndex].id),
entry: entries[entryIndex],
onDelete: (_, id) {
context
.read<FoodEntryBloc>()
.add(FoodDeletionEvent(entryID: id, forDate: date));
context.read<FoodEntryBloc>().add(FoodDeletionEvent(
entryID: id,
));
},
onChange: (_, changedEntry) {
context.read<FoodEntryBloc>().add(
FoodChangedEvent(newEntry: changedEntry, forDate: date),
);
context
.read<FoodEntryBloc>()
.add(FoodChangedEvent(newEntry: changedEntry));
},
onTap: (_, tappedEntry) {
context.read<FoodEntryBloc>().add(
FoodEntryTapped(entry: tappedEntry, forDate: date),
);
context
.read<FoodEntryBloc>()
.add(FoodEntryTapped(entry: tappedEntry));
},
),
const Divider(),

View File

@ -61,7 +61,7 @@ class _PerDatePageviewState extends State<PerDatePageview> {
return PerDateWidget(
key: ValueKey(dateToBuildWidgetFor.toString()),
date: dateToBuildWidgetFor.copyWith(isUtc: true),
date: dateToBuildWidgetFor,
onDateSelected: (dateSelected) {
if (dateSelected == null) return;

View File

@ -11,6 +11,7 @@ import 'package:calorimeter/utils/theme_switcher_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
class PerDateWidget extends StatefulWidget {
final DateTime date;
@ -25,13 +26,16 @@ class PerDateWidget extends StatefulWidget {
class _PerDateWidgetState extends State<PerDateWidget>
with AutomaticKeepAliveClientMixin<PerDateWidget> {
late FoodStorage storage;
late Future<List<FoodEntryState>> entriesFuture;
List<FoodEntryState> entries = [];
@override
void initState() {
context
.read<FoodEntryBloc>()
.add(PageBeingInitialized(forDate: widget.date));
storage = FoodStorage.getInstance();
entriesFuture = storage.getEntriesForDate(widget.date);
entriesFuture.then((val) {
entries = val;
});
super.initState();
}
@ -44,51 +48,63 @@ class _PerDateWidgetState extends State<PerDateWidget>
Widget build(BuildContext context) {
super.build(context);
return BlocConsumer<FoodEntryBloc, GlobalEntryState>(
listener: (context, pageState) {
if (pageState.errorString != null) {
showNewSnackbarWith(context, pageState.errorString!);
}
},
builder: (context, globalState) {
return Scaffold(
appBar: AppBar(
title: Text(DateFormat.yMMMMd('de').format(widget.date)),
actions: const [ThemeSwitcherButton()],
),
body: FoodEntryList(
entries: globalState.foodEntries[widget.date] ?? [],
date: widget.date),
bottomNavigationBar: BottomAppBar(
shape: const RectangularNotchShape(),
color: Theme.of(context).colorScheme.secondary,
child: SumWidget(
foodEntries: globalState.foodEntries[widget.date] ?? [])),
drawer: const AppDrawer(),
floatingActionButton: OverflowBar(children: [
ScanFoodFloatingButton(
onPressed: () {
var result = BarcodeScanner.scan();
context.read<FoodEntryBloc>().add(
BarcodeScanned(
scanResultFuture: result,
forDate: widget.date,
),
);
},
),
const SizedBox(width: 8),
CalendarFloatingButton(
startFromDate: widget.date,
onDateSelected: (dateSelected) {
widget.onDateSelected(dateSelected);
},
),
]),
floatingActionButtonLocation:
FloatingActionButtonLocation.endDocked);
},
);
return FutureBuilder(
future: entriesFuture,
builder: (context, snapshot) {
return snapshot.connectionState != ConnectionState.done
? const Center(child: CircularProgressIndicator())
: MultiProvider(
providers: [
BlocProvider(
create: (context) => FoodEntryBloc(
initialState: PageState(foodEntries: entries),
storage: storage,
forDate: widget.date,
),
)
],
child: BlocConsumer<FoodEntryBloc, PageState>(
listener: (context, pageState) {
if (pageState.errorString != null) {
showNewSnackbarWith(context, pageState.errorString!);
}
},
builder: (context, pageState) {
return Scaffold(
appBar: AppBar(
title: Text(
DateFormat.yMMMMd('de').format(widget.date)),
actions: const [ThemeSwitcherButton()],
),
body: FoodEntryList(entries: pageState.foodEntries),
bottomNavigationBar: BottomAppBar(
shape: const RectangularNotchShape(),
color: Theme.of(context).colorScheme.secondary,
child: SumWidget(
foodEntries: pageState.foodEntries)),
drawer: const AppDrawer(),
floatingActionButton: OverflowBar(children: [
ScanFoodFloatingButton(
onPressed: () {
var result = BarcodeScanner.scan();
context.read<FoodEntryBloc>().add(
BarcodeScanned(scanResultFuture: result));
},
),
const SizedBox(width: 8),
CalendarFloatingButton(
startFromDate: widget.date,
onDateSelected: (dateSelected) {
widget.onDateSelected(dateSelected);
},
),
]),
floatingActionButtonLocation:
FloatingActionButtonLocation.endDocked);
},
),
);
});
}
void showNewSnackbarWith(BuildContext context, String text) {