From d4abba2df235cbd75578bd990617043844769041 Mon Sep 17 00:00:00 2001 From: Marco Date: Mon, 23 Dec 2024 19:38:45 +0100 Subject: [PATCH] Fix handling of kcal amount extraction from json --- lib/food_entry/food_entry_bloc.dart | 6 +---- lib/food_scan/food_fact_lookup.dart | 41 ++++++++++++++++++++--------- 2 files changed, 29 insertions(+), 18 deletions(-) diff --git a/lib/food_entry/food_entry_bloc.dart b/lib/food_entry/food_entry_bloc.dart index 6f86f01..c702abf 100644 --- a/lib/food_entry/food_entry_bloc.dart +++ b/lib/food_entry/food_entry_bloc.dart @@ -170,14 +170,10 @@ class FoodEntryBloc extends Bloc { return; } - int kcalToDisplay = response.food?.kcalPer100g ?? 0; - if (response.food?.kcalPer100gPrepared != 0) { - kcalToDisplay = response.food?.kcalPer100gPrepared ?? 0; - } var newEntryFinishedWaiting = FoodEntryState( name: response.food?.name ?? "", mass: response.food?.mass ?? 0, - kcalPer100: kcalToDisplay, + kcalPer100: response.food?.kcalPer100g ?? 0, waitingForNetwork: false, isSelected: false, ); diff --git a/lib/food_scan/food_fact_lookup.dart b/lib/food_scan/food_fact_lookup.dart index 28d33d7..27f226c 100644 --- a/lib/food_scan/food_fact_lookup.dart +++ b/lib/food_scan/food_fact_lookup.dart @@ -47,35 +47,50 @@ class FoodFactLookupClient { class FoodFactModel { final String name; final int kcalPer100g; - final int kcalPer100gPrepared; final int mass; FoodFactModel({ required this.name, required this.mass, required this.kcalPer100g, - required this.kcalPer100gPrepared, }); factory FoodFactModel.fromJson(Map json) { - int kcalPer100g = json['product']['nutriments']['energy-kcal_100g'] ?? 0; - int kcalPer100gPrepared = - json['product']['nutriments']['energy-kcal_prepared_100g'] ?? 0; - - String quantityString = json['product']['product_quantity'] ?? "0"; - int quantity; + int kcalPer100gForModel = 0; + int kcalPer100g = 0; + int kcalPer100gPrepared = 0; try { - quantity = int.parse(quantityString); + kcalPer100g = (json['product']['nutriments']['energy-kcal_100g'] as num) + .toDouble() + .ceil(); + kcalPer100gForModel = kcalPer100g; + } catch (e) { + try { + kcalPer100gPrepared = + (json['product']['nutriments']['energy-kcal_prepared_100g'] as num) + .toDouble() + .ceil(); + kcalPer100gForModel = kcalPer100gPrepared; + } catch (e) { + kcalPer100gForModel = 0; + } + } + + String quantityString = json['product']['product_quantity'] ?? "0"; + double quantity; + + try { + quantity = double.parse(quantityString); } catch (e) { quantity = 0; } return FoodFactModel( - name: json['product']['product_name'] ?? "", - kcalPer100g: kcalPer100g, - kcalPer100gPrepared: kcalPer100gPrepared, - mass: quantity); + name: json['product']['product_name'] ?? "", + kcalPer100g: kcalPer100gForModel, + mass: quantity.ceil(), + ); } }