Make snackbar appear when state changes in BLoC

This commit is contained in:
Marco 2024-09-24 02:16:13 +02:00
parent 4f65425e66
commit 34ae2ead40
2 changed files with 31 additions and 5 deletions

View File

@ -47,6 +47,12 @@ class FoodEntryBloc extends Bloc<FoodEvent, PageState> {
if (scanResult.type == ResultType.Cancelled) {
return;
}
if (scanResult.type == ResultType.Error) {
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);
@ -58,6 +64,20 @@ class FoodEntryBloc extends Bloc<FoodEvent, PageState> {
await responseFuture.then((response) {
newList.removeWhere((entryState) => entryState.id == newEntryWaiting.id);
if (response.status == FoodFactResponseStatus.barcodeNotFound) {
emit(PageState(
foodEntries: state.foodEntries,
errorString: "Barcode konnte nicht gefunden werden."));
return;
}
if (response.status ==
FoodFactResponseStatus.foodFactServerNotReachable) {
emit(PageState(
foodEntries: state.foodEntries,
errorString: "OpenFoodFacts-Server konnte nicht erreicht werden."));
return;
}
var newEntryFinishedWaiting = FoodEntryState(
name: response.food?.name ?? "",
mass: response.food?.mass ?? 0,
@ -93,8 +113,9 @@ class BarcodeScanned extends FoodEvent {
/// This is the state for one date/page
class PageState {
final List<FoodEntryState> foodEntries;
final String? errorString;
PageState({required this.foodEntries});
PageState({required this.foodEntries, this.errorString});
factory PageState.init() {
return PageState(foodEntries: []);

View File

@ -56,19 +56,24 @@ class _PerDateWidgetState extends State<PerDateWidget> {
),
)
],
child: BlocBuilder<FoodEntryBloc, PageState>(
builder: (context, state) {
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: state.foodEntries),
body: FoodEntryList(entries: pageState.foodEntries),
bottomNavigationBar: BottomAppBar(
shape: const RectangularNotchShape(),
color: Theme.of(context).colorScheme.secondary,
child: SumWidget(foodEntries: state.foodEntries)),
child:
SumWidget(foodEntries: pageState.foodEntries)),
drawer: const AppDrawer(),
floatingActionButton: OverflowBar(children: [
ScanFoodFloatingButton(