From b33cb8a8e3ecc86f623ff5eaa52689f6d806191d Mon Sep 17 00:00:00 2001 From: 98spag Date: Tue, 30 May 2023 09:38:54 +0200 Subject: [PATCH] feat: add statistics component logic with dedicated box and day,week,month filtering --- .../components/MealPageFoodComponent.dart | 10 +- lib/android/components/card_component.dart | 35 +-- .../components/diet_chart_component.dart | 74 +++++++ .../components/food_list_component.dart | 26 +-- .../components/founded_search_component.dart | 35 +-- .../meal_page_text/days_component.dart | 64 +++++- .../meal_page_text/days_text_component.dart | 34 ++- lib/android/config/cast_helper.dart | 17 ++ lib/android/config/setup_todaybox_config.dart | 49 +---- lib/android/config/statistics.dart | 202 +++++++++++++++--- lib/android/models/food.dart | 2 +- lib/android/models/food.g.dart | 65 ------ lib/android/pages/nav_pages/today_page.dart | 6 +- lib/main.dart | 17 +- lib/web/component/section_component.dart | 16 +- pubspec.yaml | 1 + 16 files changed, 418 insertions(+), 235 deletions(-) create mode 100644 lib/android/components/diet_chart_component.dart create mode 100644 lib/android/config/cast_helper.dart delete mode 100644 lib/android/models/food.g.dart diff --git a/lib/android/components/MealPageFoodComponent.dart b/lib/android/components/MealPageFoodComponent.dart index f3f3038..50e2a09 100644 --- a/lib/android/components/MealPageFoodComponent.dart +++ b/lib/android/components/MealPageFoodComponent.dart @@ -1,6 +1,6 @@ import 'package:ernaehrung/android/components/food_list_component.dart'; import 'package:flutter/material.dart'; - +import 'package:hive/hive.dart'; import 'meal_page_text/title_component.dart'; class MealPageStatisticsFoodComponent extends StatelessWidget { @@ -14,12 +14,12 @@ class MealPageStatisticsFoodComponent extends StatelessWidget { ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, - children: const [ - SizedBox( + children: [ + const SizedBox( height: 24, ), - TitleComponent("Nahrung"), - FoodComponent() + const TitleComponent("Nahrung"), + FoodComponent(box: Hive.box('STATISTICS_REDUCED'),) ], ), ); diff --git a/lib/android/components/card_component.dart b/lib/android/components/card_component.dart index 8c2877f..ba35f58 100644 --- a/lib/android/components/card_component.dart +++ b/lib/android/components/card_component.dart @@ -1,15 +1,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; - import '../models/food.dart'; import '../pages/nav_pages/search_food.dart'; class CardComponent extends StatefulWidget { final String eatingMealName; final List selectedMeal; + final bool addButtonVisible; const CardComponent( - {Key? key, required this.eatingMealName, required this.selectedMeal}) + {Key? key, required this.eatingMealName, required this.selectedMeal, this.addButtonVisible = true}) : super(key: key); @override @@ -58,19 +58,24 @@ class _CardComponentState extends State { } Widget getElevatedButton() { - return ElevatedButton( - onPressed: () async { - Navigator.of(context).push(createRoute(widget.eatingMealName)); - }, - style: ElevatedButton.styleFrom( - shape: const CircleBorder(), - padding: const EdgeInsets.all(0), - ), - child: const Text( - '+', - style: TextStyle(fontSize: 28), - ), - ); + if(widget.addButtonVisible){ + return ElevatedButton( + onPressed: () async { + Navigator.of(context).push(createRoute(widget.eatingMealName)); + }, + style: ElevatedButton.styleFrom( + shape: const CircleBorder(), + padding: const EdgeInsets.all(0), + ), + child: const Text( + '+', + style: TextStyle(fontSize: 28), + ), + ); + }else{ + return const SizedBox.shrink(); + } + } int getCountedCalories() { diff --git a/lib/android/components/diet_chart_component.dart b/lib/android/components/diet_chart_component.dart new file mode 100644 index 0000000..f63bf46 --- /dev/null +++ b/lib/android/components/diet_chart_component.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:percent_indicator/linear_percent_indicator.dart'; + +class DietChatComponent extends StatefulWidget { + final double fatPercentPerThousandCalorie = 3.7; + final double proteinPercentPerThousandCalorie = 4.5; + final double carbsPercentPerThousandCalorie = 12.8; + + final String carbs = "Kohlenhydrate"; + final String protein = "Protein"; + final String fat = "Fett"; + + late String fatGramm, carbGramm, proteinGramm = ""; + late double fatSummary, carbSummary, proteinSummary = 0.0; + + DietChatComponent(int calorienSummary, {super.key, int calorienLeft = 0}){ + fatSummary = (calorienSummary / 100) * fatPercentPerThousandCalorie; + carbSummary = (calorienSummary / 100) * carbsPercentPerThousandCalorie; + proteinSummary = (calorienSummary / 100) * proteinPercentPerThousandCalorie; + fatGramm = '0 / $fatSummary g'; + carbGramm = '0 / $carbSummary g'; + proteinGramm = '0 / $proteinSummary g'; + } + + @override + State createState() => _DietChatComponentState(); +} + +class _DietChatComponentState extends State { + @override + Widget build(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + children: [ + Text(widget.carbs), + LinearPercentIndicator( + width: 100.0, + lineHeight: 8.0, + percent: 0.9, + progressColor: Colors.blue, + ), + Text(widget.carbGramm) + ], + ), + Column( + children: [ + Text(widget.protein), + LinearPercentIndicator( + width: 100.0, + lineHeight: 8.0, + percent: 0.9, + progressColor: Colors.blue, + ), + Text(widget.proteinGramm) + ], + ), + Column( + children: [ + Text(widget.fat), + LinearPercentIndicator( + width: 100.0, + lineHeight: 8.0, + percent: 0.9, + progressColor: Colors.blue, + ), + Text(widget.fatGramm) + ], + ) + ], + ); + } +} diff --git a/lib/android/components/food_list_component.dart b/lib/android/components/food_list_component.dart index 88dfff3..81075c7 100644 --- a/lib/android/components/food_list_component.dart +++ b/lib/android/components/food_list_component.dart @@ -1,26 +1,17 @@ +import 'package:ernaehrung/android/config/cast_helper.dart'; import 'package:flutter/cupertino.dart'; -import 'package:hive/hive.dart'; import 'package:hive_flutter/adapters.dart'; - -import '../models/food.dart'; import 'card_component.dart'; class FoodComponent extends StatelessWidget { - const FoodComponent({Key? key}) : super(key: key); - - List castDynamicToListFood(List dynamicList) { - List foodList = []; - for (Food element in dynamicList) { - foodList.add(element); - } - - return foodList; - } + final Box box; + const FoodComponent({super.key, required this.box}); @override Widget build(BuildContext context) { + return ValueListenableBuilder( - valueListenable: Hive.box("TODAY").listenable(), + valueListenable: box.listenable(), builder: (context, box, widget) { return ListView.builder( primary: false, @@ -32,10 +23,13 @@ class FoodComponent extends StatelessWidget { } else { return CardComponent( eatingMealName: box.keyAt(i).toString(), - selectedMeal: - castDynamicToListFood(box.getAt(i))); + selectedMeal: castDynamicToListFood(box.getAt(i)), + addButtonVisible: box.name != 'statistics_reduced', + ); } }); }); } + + } diff --git a/lib/android/components/founded_search_component.dart b/lib/android/components/founded_search_component.dart index 7d67ec9..889d645 100644 --- a/lib/android/components/founded_search_component.dart +++ b/lib/android/components/founded_search_component.dart @@ -1,9 +1,9 @@ import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; +import 'package:ernaehrung/android/config/cast_helper.dart'; import 'package:ernaehrung/android/config/statistics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:hive/hive.dart'; -import '../config/setup_todaybox_config.dart'; import '../models/food.dart'; class SearchedFoodComponent extends StatefulWidget { @@ -19,35 +19,22 @@ class _SearchFoodComponentState extends State { StatisticsService statisticsService = StatisticsService(); void storeFood() async { - statisticsService.addItemToStatisticsBox(widget.food, widget.cardName); + statisticsService.addItemToMainBox(widget.food, widget.cardName); final todayBox = Hive.box(dotenv.env['TODAY_BOX']!); if (!todayBox.isOpen){ Hive.openBox(dotenv.env['TODAY_BOX']!); } + addValuesToList(todayBox, widget.cardName, [widget.food]); + } - final todayBoxDateField = todayBox.containsKey(dotenv.env['DATE_FIELD']!.toString()); - final todayBoxEatingField = todayBox.containsKey(widget.cardName.toUpperCase().toString()); - - if (todayBoxDateField && todayBoxEatingField){ - updateFoodInStorage(todayBox); - }else{ - addFoodToStorage(todayBox); + void addValuesToList(box, String key, List newValues){ + List existingList = castDynamicToListFood(box.get(key)); + for(int i = 0; i < newValues.length;i++){ + if(!existingList.contains(newValues[i])){ + existingList.add(newValues[i]); + } } - } - - void updateFoodInStorage(dynamic todayBox) async { - final values = todayBox.get(widget.cardName.toUpperCase()); - values.add(widget.food); - - await todayBox.put(widget.cardName.toUpperCase(), values); - } - - void addFoodToStorage(dynamic todayBox) async{ - List foods = []; - foods.add(widget.food); - todayBox.put(widget.cardName.toUpperCase(), foods); - - todayBox.put(dotenv.env['DATE_FIELD']!, getFormatedTodayDate()); + box.put(key, existingList); } @override diff --git a/lib/android/components/meal_page_text/days_component.dart b/lib/android/components/meal_page_text/days_component.dart index ffc43c8..0a321a6 100644 --- a/lib/android/components/meal_page_text/days_component.dart +++ b/lib/android/components/meal_page_text/days_component.dart @@ -1,12 +1,37 @@ import 'package:ernaehrung/android/components/meal_page_text/days_text_component.dart'; -import 'package:flutter/cupertino.dart'; +import 'package:ernaehrung/android/config/statistics.dart'; +import 'package:flutter/material.dart'; -class DaysMealPageComponent extends StatelessWidget { - final String dayText = "Tag"; - final String weekText = "Woche"; - final String monthText = "Monat"; +enum TimeSpan { + day, + week, + month +} + +class DaysMealPageComponent extends StatefulWidget { const DaysMealPageComponent({Key? key}) : super(key: key); + @override + State createState() => _DaysMealPageState(); +} + + +class _DaysMealPageState extends State { + int activatedIndex = 0; + StatisticsService statisticsService = StatisticsService(); + + void updateValue(int index) { + setState(() { + activatedIndex = index; + if(activatedIndex == 0){ + statisticsService.updateReducedBoxByTimespan(TimeSpan.day); + }else if(activatedIndex == 1){ + statisticsService.updateReducedBoxByTimespan(TimeSpan.week); + }else if(activatedIndex == 2){ + statisticsService.updateReducedBoxByTimespan(TimeSpan.month); + } + }); + } @override Widget build(BuildContext context) { @@ -15,11 +40,34 @@ class DaysMealPageComponent extends StatelessWidget { child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ - DaysTextComponent(dayText), - DaysTextComponent(weekText), - DaysTextComponent(monthText), + DaysTextComponent( + timeSpan: TimeSpan.day, + textColor: activatedIndex == 0 + ? const Color(0xff47a44b) + : const Color(0xff000000), + onPressed: updateValue, + index: 0 + + ), + DaysTextComponent( + timeSpan: TimeSpan.week, + textColor: activatedIndex == 1 + ? const Color(0xff47a44b) + : const Color(0xff000000), + onPressed: updateValue, + index: 1 + ), + DaysTextComponent( + timeSpan: TimeSpan.month, + textColor: activatedIndex == 2 + ? const Color(0xff47a44b) + : const Color(0xff000000), + onPressed: updateValue, + index: 2 + ), ], ), ); } } + diff --git a/lib/android/components/meal_page_text/days_text_component.dart b/lib/android/components/meal_page_text/days_text_component.dart index a5ace69..120e535 100644 --- a/lib/android/components/meal_page_text/days_text_component.dart +++ b/lib/android/components/meal_page_text/days_text_component.dart @@ -1,18 +1,40 @@ +import 'package:ernaehrung/android/components/meal_page_text/days_component.dart'; +import 'package:ernaehrung/android/config/statistics.dart'; import 'package:flutter/material.dart'; class DaysTextComponent extends StatelessWidget { - final String name; + late final String timeSpan; + late final TimeSpan timespan; + Function(int i) onPressed; + int index; + Color textColor; + late StatisticsService statisticsService; - const DaysTextComponent(this.name, {super.key}); + DaysTextComponent({super.key, required TimeSpan timeSpan, required this.textColor, required this.onPressed, required this.index}){ + timespan = timeSpan; + switch(timeSpan){ + case TimeSpan.day: + this.timeSpan = 'Tag'; + break; + case TimeSpan.week: + this.timeSpan = 'Woche'; + break; + case TimeSpan.month: + this.timeSpan = 'Monat'; + break; + } + } @override Widget build(BuildContext context) { return TextButton( - onPressed: () {}, + onPressed: () { + onPressed(index); + }, child: Text( - name, - style: const TextStyle( - color: Color.fromARGB(255, 211, 211, 211), + timeSpan, + style: TextStyle( + color: textColor, fontSize: 14, ), )); diff --git a/lib/android/config/cast_helper.dart b/lib/android/config/cast_helper.dart new file mode 100644 index 0000000..9f510f0 --- /dev/null +++ b/lib/android/config/cast_helper.dart @@ -0,0 +1,17 @@ +import '../models/food.dart'; + +List castDynamicToListFood(List dynamicList) { + List foodList = []; + for (Food element in dynamicList) { + foodList.add(element); + } + return foodList; +} + +Map> castDynamicMap(Map dynamicMap){ + Map> foodMap = {}; + for(dynamic key in dynamicMap.keys){ + foodMap.putIfAbsent(key as String , () => castDynamicToListFood(dynamicMap[key])); + } + return foodMap; +} \ No newline at end of file diff --git a/lib/android/config/setup_todaybox_config.dart b/lib/android/config/setup_todaybox_config.dart index 505992b..5c62ef1 100644 --- a/lib/android/config/setup_todaybox_config.dart +++ b/lib/android/config/setup_todaybox_config.dart @@ -4,51 +4,22 @@ import '../models/food.dart'; final List emptyList = []; -Future setupTodayBox() async { - final todayBoxExist = await Hive.boxExists(dotenv.env['TODAY_BOX']!); - final todayBoxOpened = Hive.isBoxOpen(dotenv.env['TODAY_BOX']!); - if (!todayBoxOpened && !todayBoxExist){ - Hive.openBox(dotenv.env['TODAY_BOX']!); - } - setupEatingKeys(); -} - -void setupEatingKeys() async { +void setupTodayBox() async{ final todayBox = Hive.box(dotenv.env['TODAY_BOX']!); - final breakfastExist = todayBox.containsKey(dotenv.env['BREAKFAST_FIELD']!); - final lunchExist = todayBox.containsKey(dotenv.env['LUNCH_FIELD']!); - final dinnerExist = todayBox.containsKey(dotenv.env['DINNER_FIELD']!); - - if (!breakfastExist){ - todayBox.put(dotenv.env['BREAKFAST_FIELD']!, emptyList); - } - - if (!lunchExist){ - todayBox.put(dotenv.env['LUNCH_FIELD']!, emptyList); - } - - if (!dinnerExist){ - todayBox.put(dotenv.env['DINNER_FIELD']!, emptyList); - } - - setupDateField(); -} - -void setupDateField() async{ - final todayBox = Hive.box(dotenv.env['TODAY_BOX']!); - final dateExist = todayBox.containsKey(dotenv.env['DATE_FIELD']!); - - if (!dateExist){ - todayBox.put(dotenv.env['DATE_FIELD']!, getFormatedTodayDate()); - } -} - -void moveTodayBoxDataToYesterdayAndBefore() async{ + putIfKeyNotExists(todayBox, 'FRÜHSTÜCK', []); + putIfKeyNotExists(todayBox, 'MITTAGESSEN', []); + putIfKeyNotExists(todayBox, 'ABENDESSEN', []); } + +void putIfKeyNotExists(Box box, String key, List value) { + if (!box.containsKey(key)) { + box.put(key, value); + } +} String getFormatedTodayDate(){ return DateTime.now().toString().substring(0,10); } \ No newline at end of file diff --git a/lib/android/config/statistics.dart b/lib/android/config/statistics.dart index bb0286b..86c2ae4 100644 --- a/lib/android/config/statistics.dart +++ b/lib/android/config/statistics.dart @@ -1,49 +1,185 @@ -import 'package:hive/hive.dart'; +import 'dart:math'; +import 'package:ernaehrung/android/components/meal_page_text/days_component.dart'; +import 'package:ernaehrung/android/config/cast_helper.dart'; +import 'package:hive/hive.dart'; import '../models/food.dart'; class StatisticsService { - - final String boxName = 'STATISTICS'; + final String reducedStatisticsBoxName = 'STATISTICS_REDUCED'; + final String mainStatisticsBoxName = 'STATISTICS_MAIN'; StatisticsService() { - initBox(); + initBoxes(); } - initBox()async{ - await Hive.openBox(boxName); + initBoxes()async{ + Box reducedBox = Hive.box(reducedStatisticsBoxName); + putIfKeyNotExists(reducedBox, 'FRÜHSTÜCK', []); + putIfKeyNotExists(reducedBox, 'MITTAGESSEN', []); + putIfKeyNotExists(reducedBox, 'ABENDESSEN', []); + updateReducedBoxByTimespan(TimeSpan.day); } + void putIfKeyNotExists(Box box, String key, dynamic value) { + if (!box.containsKey(key)) { + box.put(key, value); + } + } - addItemToStatisticsBox(Food value, String mealType){ + updateReducedBoxByTimespan(TimeSpan timeSpan){ + clearReducedBoxBeforeUpdate(); + print(timeSpan); + DateTime now = DateTime.now(); + int timestamp = now.millisecondsSinceEpoch.toInt() ~/ 1000; + switch(timeSpan){ + case TimeSpan.day: + getNewFoodAndUpdateReducedBoxByTimestamp(timestamp); + break; + case TimeSpan.week: + List currentWeek = getTimestampsByTimestampAndTimespan(TimeSpan.week,timestamp); + for(int i = 0;i < currentWeek.length;i++){ + getNewFoodAndUpdateReducedBoxByTimestamp(currentWeek[i]); + } + break; + case TimeSpan.month: + List currentWeek = getTimestampsByTimestampAndTimespan(TimeSpan.month,timestamp); + for(int i = 0;i < currentWeek.length;i++){ + getNewFoodAndUpdateReducedBoxByTimestamp(currentWeek[i]); + } + break; + } + } + + void getNewFoodAndUpdateReducedBoxByTimestamp(int timestamp){ + Map> newFood = getFoodMapForGivenTimestampFromMainBox(timestamp); + if(newFood.keys.isNotEmpty){ + setElementsOfReducedBox(newFood); + } + } + + List getTimestampsByTimestampAndTimespan(TimeSpan timespan, int timestamp) { + int range = timespan == TimeSpan.week ? 7 : 31; + int targetWeekday = DateTime.monday; // Example target weekday (Monday) + DateTime currentDateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + int currentWeekday = currentDateTime.weekday; + int daysToAdd = targetWeekday - currentWeekday; + DateTime targetDateTime = currentDateTime.add(Duration(days: daysToAdd)); + + List timestampsForWeekdays = []; + for (int i = 0; i < range; i++) { + timestampsForWeekdays.add(targetDateTime.millisecondsSinceEpoch ~/ 1000); + targetDateTime = targetDateTime.add(const Duration(days: 1)); + } + return timestampsForWeekdays; + } + + clearReducedBoxBeforeUpdate(){ + Box box = Hive.box(reducedStatisticsBoxName); + for(int i = 0; i < box.keys.length;i++){ + box.put(box.keys.elementAt(i), []); + } + } + setElementsOfReducedBox(Map> newFood){ + Box box = Hive.box(reducedStatisticsBoxName); + Iterable keys = newFood.keys; + for(int i = 0; i < keys.length;i++){ + addValuesToList(box, keys.elementAt(i), newFood[keys.elementAt(i)] ?? []); + } + } + + void addValuesToList(Box box, String key, List newValues){ + List existingList = castDynamicToListFood(box.get(key)); + for(int i = 0; i < newValues.length;i++){ + if(!existingList.contains(newValues[i])){ + existingList.add(newValues[i]); + } + } + box.put(key, existingList); + } + + getDayAsIntFromTimestamp(int timestamp){ + DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + return dateTime.day; + } + + Map> getFoodMapForGivenTimestampFromMainBox(int timestamp){ + Box box = Hive.box(mainStatisticsBoxName); + dynamic matchingTimestamp = getMatchingTimeStamp(box, timestamp); + if(matchingTimestamp != null){ + return castDynamicMap(box.get(matchingTimestamp)); + } + return >{}; + } + + getMatchingTimeStamp(Box box,int newTimestamp){ + if(box.keys.isNotEmpty){ + for(int i = 0; i < box.keys.length;i++){ + int timestamp = box.keys.elementAt(i); + if(isDateEqual(newTimestamp, timestamp)){ + return timestamp; + } + } + return null; + } + } + + getMonthAsIntFromTimestamp(int timestamp){ + DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + return dateTime.month; + } + + getYearAsIntFromTimestamp(int timestamp){ + DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + return dateTime.year; + } + + isDateEqual(int timestamp1, int timestamp2){ + return + getDayAsIntFromTimestamp(timestamp1) == getDayAsIntFromTimestamp(timestamp2) && + getMonthAsIntFromTimestamp(timestamp1) == getMonthAsIntFromTimestamp(timestamp2) && + getYearAsIntFromTimestamp(timestamp1) == getYearAsIntFromTimestamp(timestamp2); + } + + addItemToMainBox(Food value, String mealType){ // Hive.deleteFromDisk(); - Box box = Hive.box(boxName); + Box box = Hive.box(mainStatisticsBoxName); DateTime dateTime = DateTime.now(); - int timestamp = dateTime.millisecondsSinceEpoch.toInt() ~/ 1000; - print(timestamp); - Map>? valueMap = box.get(timestamp); - valueMap ??= { - "FRÜHSTÜCK": [], - "MITTAGESSEN": [], - "ABENDESSEN": [] - }; + + // DEBUG + //DateTime dateTime = getRandomTimestampForTesting(); + + int newTimestamp = dateTime.millisecondsSinceEpoch.toInt() ~/ 1000; + + dynamic matchingTimestamp = getMatchingTimeStamp(box, newTimestamp); + if(matchingTimestamp != null){ + newTimestamp = matchingTimestamp; + } + Map>? valueMap = castDynamicMap(box.get(newTimestamp)); List values = []; if(valueMap.containsKey(mealType)){ values = valueMap[mealType]!; } values.add(value); valueMap[mealType] = values; - box.put(timestamp, valueMap); - showItems(); + box.put(newTimestamp, valueMap); } - num getAllCaloriesByTimestamp(DateTime date){ - Box box = Hive.box(boxName); + getRandomTimestampForTesting(){ + DateTime now = DateTime.now(); + DateTime startOfWeek = now.subtract(Duration(days: now.weekday - 1)); + DateTime endOfWeek = startOfWeek.add(Duration(days: 6)); + + Random random = Random(); + int randomMilliseconds = random.nextInt(endOfWeek.millisecondsSinceEpoch - startOfWeek.millisecondsSinceEpoch); + DateTime randomTimestamp = startOfWeek.add(Duration(milliseconds: randomMilliseconds)); + + return randomTimestamp; + } + + num getAllCaloriesByBoxAndTimestamp(Box box,DateTime date){ int timestamp = date.millisecondsSinceEpoch.toInt() ~/ 1000; - Map>? valueMap = box.get(timestamp); - if(valueMap == null){ - return 0; - } + Map>? valueMap = castDynamicMap(box.get(timestamp)); num sum = 0; for(var mealType in valueMap.keys){ if(valueMap.containsKey(mealType)){ @@ -56,13 +192,9 @@ class StatisticsService { return sum; } - num getCaloriesByTimestampAndMealType(DateTime date, String mealType){ - Box box = Hive.box(boxName); + num getCaloriesByTimestampAndMealTypeAndBox(Box box,DateTime date, String mealType){ int timestamp = date.millisecondsSinceEpoch.toInt() ~/ 1000; - Map>? valueMap = box.get(timestamp); - if(valueMap == null){ - return 0; - } + Map>? valueMap = castDynamicMap(box.get(timestamp)); num sum = 0; if(valueMap.containsKey(mealType)){ List values = valueMap[mealType]!; @@ -74,8 +206,14 @@ class StatisticsService { } showItems(){ - print("ITEMS"); - print(Hive.box(boxName).keys); + print("Statistics.dart - showItems() - ITEMS"); + //Hive.box(boxName).clear(); + print(Hive.box(mainStatisticsBoxName).keys.length); + for(int i = 0; i < Hive.box(mainStatisticsBoxName).keys.length; i++){ + print(Hive.box(mainStatisticsBoxName).keys.elementAt(i)); + print(Hive.box(mainStatisticsBoxName).values.elementAt(i)); + //print(Hive.box(boxName).keys.elementAt(i) + " " + Hive.box(boxName).values.elementAt(i)); + } } } \ No newline at end of file diff --git a/lib/android/models/food.dart b/lib/android/models/food.dart index 5bc8911..7c0f192 100644 --- a/lib/android/models/food.dart +++ b/lib/android/models/food.dart @@ -1,7 +1,7 @@ import 'package:hive/hive.dart'; part 'food.g.dart'; -@HiveType(typeId: 1) +@HiveType(typeId: 0) class Food { Food(this.id, this.name, this.foodGroup, this.calories, this.fatg, this.proteing, this.carbohydrateg, this.sugarsg, this.fiberg); diff --git a/lib/android/models/food.g.dart b/lib/android/models/food.g.dart deleted file mode 100644 index ada01fc..0000000 --- a/lib/android/models/food.g.dart +++ /dev/null @@ -1,65 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'food.dart'; - -// ************************************************************************** -// TypeAdapterGenerator -// ************************************************************************** - -class FoodAdapter extends TypeAdapter { - @override - final int typeId = 1; - - @override - Food read(BinaryReader reader) { - final numOfFields = reader.readByte(); - final fields = { - for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), - }; - return Food( - fields[0] as dynamic, - fields[1] as dynamic, - fields[2] as dynamic, - fields[3] as dynamic, - fields[4] as dynamic, - fields[5] as dynamic, - fields[6] as dynamic, - fields[7] as dynamic, - fields[8] as dynamic, - ); - } - - @override - void write(BinaryWriter writer, Food obj) { - writer - ..writeByte(9) - ..writeByte(0) - ..write(obj.id) - ..writeByte(1) - ..write(obj.name) - ..writeByte(2) - ..write(obj.foodGroup) - ..writeByte(3) - ..write(obj.calories) - ..writeByte(4) - ..write(obj.fatg) - ..writeByte(5) - ..write(obj.proteing) - ..writeByte(6) - ..write(obj.carbohydrateg) - ..writeByte(7) - ..write(obj.sugarsg) - ..writeByte(8) - ..write(obj.fiberg); - } - - @override - int get hashCode => typeId.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is FoodAdapter && - runtimeType == other.runtimeType && - typeId == other.typeId; -} diff --git a/lib/android/pages/nav_pages/today_page.dart b/lib/android/pages/nav_pages/today_page.dart index cef0a10..9ae7533 100644 --- a/lib/android/pages/nav_pages/today_page.dart +++ b/lib/android/pages/nav_pages/today_page.dart @@ -1,21 +1,19 @@ import 'package:ernaehrung/android/components/food_list_component.dart'; import 'package:flutter/material.dart'; +import 'package:hive/hive.dart'; import '../../components/diet_chart_component.dart'; import '../../components/statistics_circular_indicator_component.dart'; class TodayPage extends StatefulWidget { final String title; final Color backgroundColor = const Color(0xff47a44b); - const TodayPage({Key? key, required this.title}) : super(key: key); - @override State createState() => _TodayPageState(); } class _TodayPageState extends State { - @override Widget build(BuildContext context) { return Scaffold( @@ -36,7 +34,7 @@ class _TodayPageState extends State { children: [ StatisticsPercentComponent(300, 100, 400), DietChatComponent(1500), - const FoodComponent(), + FoodComponent(box: Hive.box('TODAY'),), ], ), )), diff --git a/lib/main.dart b/lib/main.dart index 300297e..8275278 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,24 +1,27 @@ - +import 'package:ernaehrung/android/models/food.dart'; import 'package:ernaehrung/web/web_app.dart'; import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'android/andoird_app.dart'; -import 'android/config/setup_todaybox_config.dart'; -import 'android/models/food.dart'; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb; +import 'android/config/setup_todaybox_config.dart'; + void main() async { await dotenv.load(fileName: ".env"); await Hive.initFlutter(); - if (!Hive.isAdapterRegistered(1)) { + if(!Hive.isAdapterRegistered(0)){ Hive.registerAdapter(FoodAdapter()); } + //await Hive.deleteFromDisk(); - - await Hive.openBox(dotenv.env['TODAY_BOX']!); - await setupTodayBox(); + await Hive.openBox('STATISTICS_REDUCED'); + await Hive.openBox('STATISTICS_MAIN'); + await Hive.openBox('TODAY'); + setupTodayBox(); + //Hive.deleteFromDisk(); if(defaultTargetPlatform == TargetPlatform.android){ runApp(const AndroidApp()); diff --git a/lib/web/component/section_component.dart b/lib/web/component/section_component.dart index 2ba68cd..7f49866 100644 --- a/lib/web/component/section_component.dart +++ b/lib/web/component/section_component.dart @@ -1,23 +1,13 @@ import 'package:ernaehrung/android/components/statistics_circular_indicator_component.dart'; +import 'package:ernaehrung/android/config/cast_helper.dart'; import 'package:flutter/cupertino.dart'; import 'package:hive_flutter/adapters.dart'; - import '../../android/components/card_component.dart'; import '../../android/components/diet_chart_component.dart'; -import '../../android/models/food.dart'; class SectionComponent extends StatelessWidget { const SectionComponent({Key? key}) : super(key: key); - List castDynamicToListFood(List dynamicList) { - List foodList = []; - for (Food element in dynamicList) { - foodList.add(element); - } - - return foodList; - } - @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -38,8 +28,8 @@ class SectionComponent extends StatelessWidget { }else{ return CardComponent( eatingMealName: box.keyAt(i).toString(), - selectedMeal: castDynamicToListFood( - box.getAt(i))); + selectedMeal: castDynamicToListFood(box.getAt(i)), + ); } } ); diff --git a/pubspec.yaml b/pubspec.yaml index b7601e2..9cb1128 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -61,6 +61,7 @@ dev_dependencies: hive_generator: ^2.0.0 build_runner: ^2.3.3 + # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec