From 62f3b076900b243845777f518adce44ce29e26fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Thu, 11 Mar 2021 20:47:44 +0000 Subject: [PATCH 01/58] =?UTF-8?q?Translated=20using=20Weblate=20(Norwegian?= =?UTF-8?q?=20Bokm=C3=A5l)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently translated at 100.0% (52 of 52 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/nb_NO/ --- lib/l10n/app_nb.arb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/l10n/app_nb.arb b/lib/l10n/app_nb.arb index 4b83d5a08..e0375f6a6 100644 --- a/lib/l10n/app_nb.arb +++ b/lib/l10n/app_nb.arb @@ -1,5 +1,5 @@ { - "aboutText": "wger arbeidsøkthåndterer er gemenhetslig fri programvare, lisensiert GPLv3+ og tilgjengelig på GitHub:", + "aboutText": "wger arbeidsøkthåndterer er gemenhetslig fri programvare, lisensiert AGPLv3+ og tilgjengelig på GitHub:", "@aboutText": { "description": "Text in the about dialog" }, From d1da745d5875656895a752aa134e0ef3da653c24 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 12 Mar 2021 11:45:14 +0100 Subject: [PATCH 02/58] Move form elements to listview to allow for scrolling --- lib/widgets/workouts/forms.dart | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index 936d580d3..44c5143ed 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -340,18 +340,25 @@ class _SetFormWidgetState extends State { Text('If you do the same repetitions for all sets you can just enter ' 'one value: e.g. for 4 sets just enter one "10" for the repetitions, ' 'this automatically becomes "4 x 10".'), - ...widget._set.exercisesObj.map((exercise) { - final settings = - widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); + SizedBox( + height: 350, + child: ListView( + children: [ + ...widget._set.exercisesObj.map((exercise) { + final settings = + widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); - return ExerciseSetting( - exercise, - settings, - _detailed, - _currentSetSliderValue, - removeExercise, - ); - }).toList(), + return ExerciseSetting( + exercise, + settings, + _detailed, + _currentSetSliderValue, + removeExercise, + ); + }).toList(), + ], + ), + ), ElevatedButton( child: Text(AppLocalizations.of(context).save), onPressed: () async { From cc729f305b5a5a6d5e624f4f8b27cebf36186588 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 12 Mar 2021 13:07:52 +0100 Subject: [PATCH 03/58] Replace more unstranslated strings --- lib/l10n/app_en.arb | 27 ++++++++++++++++++++++++++ lib/screens/dashboard.dart | 2 +- lib/widgets/dashboard/calendar.dart | 17 +++++++++------- lib/widgets/dashboard/widgets.dart | 4 ++-- lib/widgets/nutrition/forms.dart | 6 +++--- lib/widgets/weight/forms.dart | 4 ++-- lib/widgets/workouts/gym_mode.dart | 2 +- lib/widgets/workouts/log.dart | 11 ++++++----- lib/widgets/workouts/workout_logs.dart | 11 +++++------ 9 files changed, 57 insertions(+), 27 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 627507f79..663ef66b5 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -58,6 +58,8 @@ "@gymMode": { "description": "Label when starting the gym mode" }, + "logHelpEntries": "If on a single day there is more than one entry with the same number of repetitions, but different weights, only the entry with the higher weight is shown in the diagram.", + "logHelpEntriesUnits": "Note that only entries with a weight unit (kg or lb) and repetitions are charted, other combinations such as time or until failure are ignored here.", "description": "Description", "@description": {}, "save": "Save", @@ -138,10 +140,18 @@ "@amount": { "description": "The amount (e.g. in grams) of an ingredient in a meal" }, + "unit": "Unit", + "@unit": { + "description": "The unit used for a repetition (kg, time, etc.)" + }, "newEntry": "New entry", "@newEntry": { "description": "Title when adding a new entry such as a weight or log entry" }, + "noWeightEntries": "You have no weight entries", + "@noWeightEntries": { + "description": "Message shown when the user has no logged weight entries" + }, "edit": "Edit", "@edit": {}, "loadingText": "Loading...", @@ -159,5 +169,22 @@ "aboutText": "wger is copylefted libre software, licensed GPLv3+ and available on GitHub:", "@aboutText": { "description": "Text in the about dialog" + }, + "calendar": "Calendar", + "goToToday": "Go to today", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "enterValue": "Please enter a value", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "enterValidNumber": "Please enter a valid number", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "selectIngredient": "Please select an ingredient", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" } } diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index b60832b0c..a69bcd93a 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -101,7 +101,7 @@ class _DashboardScreenState extends State { DashboardWeightWidget(context: context), Container( height: 650, // TODO: refactor calendar so we can get rid of size - child: DashboardCalendarWidget(title: 'Calendar'), + child: DashboardCalendarWidget(), ), ], ), diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index 1a305455b..9b47a3b25 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -30,6 +30,8 @@ import 'package:wger/providers/workout_plans.dart'; import 'package:wger/theme/theme.dart'; // Example holidays +// +// (perhaps we can do something with this, such as marking future training days?) final Map _holidays = { DateTime(2021, 1, 1): ['New Year\'s Day'], DateTime(2021, 1, 6): ['Epiphany'], @@ -62,9 +64,7 @@ class Event { } class DashboardCalendarWidget extends StatefulWidget { - DashboardCalendarWidget({Key key, this.title}) : super(key: key); - - final String title; + DashboardCalendarWidget({Key key}) : super(key: key); @override _DashboardCalendarWidgetState createState() => _DashboardCalendarWidgetState(); @@ -136,7 +136,7 @@ class _DashboardCalendarWidgetState extends State // Add events to lists _events[date].add(Event( EventType.session, - 'Impression: ${session.impressionAsString} $time', + '${AppLocalizations.of(context).impression}: ${session.impressionAsString} $time', )); } }); @@ -185,7 +185,11 @@ class _DashboardCalendarWidgetState extends State mainAxisSize: MainAxisSize.max, children: [ const SizedBox(height: 8.0), - Text(widget.title, style: Theme.of(context).textTheme.headline4), + Text( + AppLocalizations.of(context).calendar, + style: Theme.of(context).textTheme.headline4, + ), + // Switch out 2 lines below to play with TableCalendar's settings //----------------------- _buildTableCalendar(), @@ -193,7 +197,6 @@ class _DashboardCalendarWidgetState extends State const SizedBox(height: 8.0), _buildButtons(), const SizedBox(height: 8.0), - //_buildEventList(), Expanded(child: _buildEventList()), ], ), @@ -358,7 +361,7 @@ class _DashboardCalendarWidgetState extends State mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( - child: Text('Go to today'), + child: Text(AppLocalizations.of(context).goToToday), onPressed: () async { final today = DateTime.now(); _calendarController.setSelectedDay( diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index baeee5c44..8f81a12eb 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -149,7 +149,7 @@ class _DashboardWeightWidgetState extends State { : Container( alignment: Alignment.center, height: 150, - child: Text('You have no weight entries'), + child: Text(AppLocalizations.of(context).noWeightEntries), ), Row( mainAxisAlignment: MainAxisAlignment.end, @@ -213,7 +213,7 @@ class _DashboardWorkoutWidgetState extends State { ...set.settings.map((s) { return Column( children: [ - Text(s.exerciseObj.name, style: TextStyle(fontWeight: FontWeight.bold)), + Text(s.exerciseObj.name), Text(s.repsText), SizedBox(height: 10), ], diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index fca1d0d5d..b831f1ae0 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -145,10 +145,10 @@ class MealItemForm extends StatelessWidget { }, validator: (value) { if (value.isEmpty) { - return 'Please select an ingredient'; + return AppLocalizations.of(context).selectIngredient; } if (mealItem.ingredientId == null) { - return 'Please select an ingredient'; + return AppLocalizations.of(context).selectIngredient; } return null; }, @@ -165,7 +165,7 @@ class MealItemForm extends StatelessWidget { try { double.parse(value); } catch (error) { - return 'Please enter a valid number'; + return AppLocalizations.of(context).enterValidNumber; } return null; }, diff --git a/lib/widgets/weight/forms.dart b/lib/widgets/weight/forms.dart index 80f1416f2..aff44639a 100644 --- a/lib/widgets/weight/forms.dart +++ b/lib/widgets/weight/forms.dart @@ -61,12 +61,12 @@ class WeightForm extends StatelessWidget { }, validator: (value) { if (value.isEmpty) { - return 'Please enter a weight'; + return AppLocalizations.of(context).enterValue; } try { double.parse(value); } catch (error) { - return 'Please enter a valid number'; + return AppLocalizations.of(context).enterValidNumber; } return null; }, diff --git a/lib/widgets/workouts/gym_mode.dart b/lib/widgets/workouts/gym_mode.dart index 96cc3d943..a72706619 100644 --- a/lib/widgets/workouts/gym_mode.dart +++ b/lib/widgets/workouts/gym_mode.dart @@ -211,7 +211,7 @@ class LogPage extends StatelessWidget { try { double.parse(value); } catch (error) { - return 'Please enter a valid number'; + return AppLocalizations.of(context).enterValidNumber; } return null; }, diff --git a/lib/widgets/workouts/log.dart b/lib/widgets/workouts/log.dart index 6551ded0c..3716f41a5 100644 --- a/lib/widgets/workouts/log.dart +++ b/lib/widgets/workouts/log.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/exercises/exercise.dart'; @@ -90,11 +91,11 @@ class ExerciseLog extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - Text('Amount'), - Text('Unit'), - Text('Weight'), - Text('Unit'), - Text('RiR'), + Text(AppLocalizations.of(context).amount), + Text(AppLocalizations.of(context).unit), + Text(AppLocalizations.of(context).weight), + Text(AppLocalizations.of(context).unit), + Text(AppLocalizations.of(context).rir), ], ), ], diff --git a/lib/widgets/workouts/workout_logs.dart b/lib/widgets/workouts/workout_logs.dart index 626e50c28..4ab710312 100644 --- a/lib/widgets/workouts/workout_logs.dart +++ b/lib/widgets/workouts/workout_logs.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/screens/workout_plan_screen.dart'; import 'package:wger/widgets/workouts/log.dart'; @@ -47,6 +48,7 @@ class _WorkoutLogsState extends State { style: Theme.of(context).textTheme.headline5, ), ), + /* Padding( padding: const EdgeInsets.all(8.0), child: Text( @@ -55,21 +57,18 @@ class _WorkoutLogsState extends State { textAlign: TextAlign.justify, ), ), + */ Padding( padding: const EdgeInsets.all(8.0), child: Text( - 'If on a single day there is more than one entry with the same' - 'number of repetitions, but different weights, only the entry with' - 'the higher weight is shown in the diagram.', + AppLocalizations.of(context).logHelpEntries, textAlign: TextAlign.justify, ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( - 'Note that only entries with a weight unit (kg or lb) and repetitions' - 'are charted, other combinations such as time or until failure' - 'are ignored here.', + AppLocalizations.of(context).logHelpEntriesUnits, textAlign: TextAlign.justify, ), ), From 676e53bd9b65ae97c6f419871221c91906231e52 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 12 Mar 2021 13:12:50 +0100 Subject: [PATCH 04/58] Workout day dismissible only starts the gym mode The regular log entry forms will come later --- lib/widgets/app_drawer.dart | 2 ++ lib/widgets/workouts/day.dart | 3 +++ 2 files changed, 5 insertions(+) diff --git a/lib/widgets/app_drawer.dart b/lib/widgets/app_drawer.dart index 7f84ab00d..610888d2c 100644 --- a/lib/widgets/app_drawer.dart +++ b/lib/widgets/app_drawer.dart @@ -77,6 +77,7 @@ class AppDrawer extends StatelessWidget { Expanded(child: Container()), */ + /* ListTile( //dense: true, leading: Icon(Icons.build), @@ -98,6 +99,7 @@ class AppDrawer extends StatelessWidget { ); }, ), + */ ListTile( //dense: true, leading: Icon(Icons.exit_to_app), diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 5f838256a..c156e688d 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -131,6 +131,7 @@ class DayHeaderDismissible extends StatelessWidget { Widget build(BuildContext context) { return Dismissible( key: Key(_day.id.toString()), + direction: DismissDirection.startToEnd, child: Container( decoration: BoxDecoration(color: Colors.black12), padding: const EdgeInsets.symmetric(vertical: 10), @@ -145,6 +146,7 @@ class DayHeaderDismissible extends StatelessWidget { ], ), ), + /* secondaryBackground: Container( color: Theme.of(context).primaryColor, padding: EdgeInsets.only(right: 10), @@ -162,6 +164,7 @@ class DayHeaderDismissible extends StatelessWidget { ], ), ), + */ background: Container( color: Theme.of(context).accentColor, alignment: Alignment.centerLeft, From fd10731d81644add6be5abc7c67c4d6aafdc18d4 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 12 Mar 2021 13:31:16 +0100 Subject: [PATCH 05/58] Make showFormBottomSheet a bit more configurable Most dialogs are small enough that they don't need to take all that space, also the controls should be as near to the user's fingers as possible --- lib/widgets/core/bottom_sheet.dart | 5 +++-- lib/widgets/nutrition/meal.dart | 1 + lib/widgets/nutrition/nutritional_plan_detail.dart | 4 ++-- lib/widgets/workouts/day.dart | 1 + lib/widgets/workouts/workout_plan_detail.dart | 5 ++--- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/widgets/core/bottom_sheet.dart b/lib/widgets/core/bottom_sheet.dart index bfd6e4b63..accb401b5 100644 --- a/lib/widgets/core/bottom_sheet.dart +++ b/lib/widgets/core/bottom_sheet.dart @@ -18,9 +18,10 @@ import 'package:flutter/material.dart'; -Future showFormBottomSheet(BuildContext context, String header, Widget form) async { +Future showFormBottomSheet(BuildContext context, String header, Widget form, + {bool scrollControlled: false}) async { return showModalBottomSheet( - isScrollControlled: true, + isScrollControlled: scrollControlled, context: context, builder: (BuildContext ctx) { return Column( diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index 3d7641bcd..c321d4311 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -74,6 +74,7 @@ class _MealWidgetState extends State { context, AppLocalizations.of(context).addIngredient, MealItemForm(widget._meal), + scrollControlled: true, ); }, ), diff --git a/lib/widgets/nutrition/nutritional_plan_detail.dart b/lib/widgets/nutrition/nutritional_plan_detail.dart index 32e7e008f..41bfb0461 100644 --- a/lib/widgets/nutrition/nutritional_plan_detail.dart +++ b/lib/widgets/nutrition/nutritional_plan_detail.dart @@ -43,7 +43,7 @@ class NutritionalPlanDetailWidget extends StatelessWidget { Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( - child: Text(AppLocalizations.of(context).add), + child: Text(AppLocalizations.of(context).addMeal), onPressed: () { showFormBottomSheet( context, @@ -131,7 +131,7 @@ class NutritionalPlanDetailWidget extends StatelessWidget { children: [ Text(''), Text( - '${AppLocalizations.of(context).energy} (${AppLocalizations.of(context).kcal}'), + '${AppLocalizations.of(context).energy} (${AppLocalizations.of(context).kcal})'), Text( '${AppLocalizations.of(context).protein} (${AppLocalizations.of(context).g})'), Text( diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index c156e688d..00b7fd355 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -106,6 +106,7 @@ class WorkoutDayWidget extends StatelessWidget { context, AppLocalizations.of(context).newSet, SetFormWidget(_day), + scrollControlled: true, ); }, ), diff --git a/lib/widgets/workouts/workout_plan_detail.dart b/lib/widgets/workouts/workout_plan_detail.dart index bc4e0230c..83bee4b8a 100644 --- a/lib/widgets/workouts/workout_plan_detail.dart +++ b/lib/widgets/workouts/workout_plan_detail.dart @@ -60,9 +60,8 @@ class _WorkoutPlanDetailState extends State { showFormBottomSheet( context, AppLocalizations.of(context).newDay, - DayFormWidget( - workout: widget._workoutPlan, - ), + DayFormWidget(workout: widget._workoutPlan), + scrollControlled: true, ); }, ), From df8bd5557b67e641a8ea66b1ea08f96222c58422 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 12 Mar 2021 20:26:19 +0100 Subject: [PATCH 06/58] Move forms in gym mode to the bottom of the screen --- lib/widgets/workouts/gym_mode.dart | 316 ++++++++++++++--------------- 1 file changed, 156 insertions(+), 160 deletions(-) diff --git a/lib/widgets/workouts/gym_mode.dart b/lib/widgets/workouts/gym_mode.dart index a72706619..11cd5fc39 100644 --- a/lib/widgets/workouts/gym_mode.dart +++ b/lib/widgets/workouts/gym_mode.dart @@ -192,47 +192,46 @@ class LogPage extends StatelessWidget { style: Theme.of(context).textTheme.headline5, ), ), - Expanded( - child: Form( - key: _form, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - TextFormField( - decoration: - InputDecoration(labelText: AppLocalizations.of(context).repetitions), - controller: _repsController, - keyboardType: TextInputType.number, - onFieldSubmitted: (_) {}, - onSaved: (newValue) { - _log.reps = int.parse(newValue); - }, - validator: (value) { - try { - double.parse(value); - } catch (error) { - return AppLocalizations.of(context).enterValidNumber; - } - return null; - }, - ), - TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).weight), - controller: _weightController, - keyboardType: TextInputType.number, - onFieldSubmitted: (_) {}, - onSaved: (newValue) { - _log.weight = double.parse(newValue); - }, - ), - TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).rir), - controller: _rirController, - keyboardType: TextInputType.number, - onFieldSubmitted: (_) {}, - onSaved: (newValue) {}, - ), - /* + Expanded(child: Container()), + Form( + key: _form, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + TextFormField( + decoration: InputDecoration(labelText: AppLocalizations.of(context).repetitions), + controller: _repsController, + keyboardType: TextInputType.number, + onFieldSubmitted: (_) {}, + onSaved: (newValue) { + _log.reps = int.parse(newValue); + }, + validator: (value) { + try { + double.parse(value); + } catch (error) { + return AppLocalizations.of(context).enterValidNumber; + } + return null; + }, + ), + TextFormField( + decoration: InputDecoration(labelText: AppLocalizations.of(context).weight), + controller: _weightController, + keyboardType: TextInputType.number, + onFieldSubmitted: (_) {}, + onSaved: (newValue) { + _log.weight = double.parse(newValue); + }, + ), + TextFormField( + decoration: InputDecoration(labelText: AppLocalizations.of(context).rir), + controller: _rirController, + keyboardType: TextInputType.number, + onFieldSubmitted: (_) {}, + onSaved: (newValue) {}, + ), + /* TextFormField( decoration: InputDecoration(labelText: AppLocalizations.of(context).comment), controller: _commentController, @@ -245,34 +244,33 @@ class LogPage extends StatelessWidget { ), */ - ElevatedButton( - child: Text(AppLocalizations.of(context).save), - onPressed: () async { - // Validate and save the current values to the weightEntry - final isValid = _form.currentState.validate(); - if (!isValid) { - return; - } - _form.currentState.save(); + ElevatedButton( + child: Text(AppLocalizations.of(context).save), + onPressed: () async { + // Validate and save the current values to the weightEntry + final isValid = _form.currentState.validate(); + if (!isValid) { + return; + } + _form.currentState.save(); - // Save the entry on the server - try { - await Provider.of(context, listen: false).addLog(_log); - //final snackBar = SnackBar(content: Text('Yay! A SnackBar!')); - //ScaffoldMessenger.of(context).showSnackBar(snackBar); - _controller.nextPage( - duration: Duration(milliseconds: 200), - curve: Curves.bounceIn, - ); - } on WgerHttpException catch (error) { - showHttpExceptionErrorDialog(error, context); - } catch (error) { - showErrorDialog(error, context); - } - }, - ), - ], - ), + // Save the entry on the server + try { + await Provider.of(context, listen: false).addLog(_log); + //final snackBar = SnackBar(content: Text('Yay! A SnackBar!')); + //ScaffoldMessenger.of(context).showSnackBar(snackBar); + _controller.nextPage( + duration: Duration(milliseconds: 200), + curve: Curves.bounceIn, + ); + } on WgerHttpException catch (error) { + showHttpExceptionErrorDialog(error, context); + } catch (error) { + showErrorDialog(error, context); + } + }, + ), + ], ), ), NavigationFooter(_controller), @@ -345,103 +343,101 @@ class _SessionPageState extends State { style: Theme.of(context).textTheme.headline5, ), ), - Expanded( - child: Form( - key: _form, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - FormField( - builder: (FormFieldState state) { - return InputDecorator( - decoration: InputDecoration( - labelText: AppLocalizations.of(context).impression, + Expanded(child: Container()), + Form( + key: _form, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + FormField( + builder: (FormFieldState state) { + return InputDecorator( + decoration: InputDecoration( + labelText: AppLocalizations.of(context).impression, + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: impressionValue, + isDense: true, + onChanged: (int newValue) { + setState(() { + impressionValue = newValue; + state.didChange(newValue); + }); + }, + items: ImpressionMap.keys.map>((int key) { + return DropdownMenuItem( + value: key, + child: Text( + ImpressionMap[key], + ), + ); + }).toList(), ), - child: DropdownButtonHideUnderline( - child: DropdownButton( - value: impressionValue, - isDense: true, - onChanged: (int newValue) { - setState(() { - impressionValue = newValue; - state.didChange(newValue); - }); - }, - items: ImpressionMap.keys.map>((int key) { - return DropdownMenuItem( - value: key, - child: Text( - ImpressionMap[key], - ), - ); - }).toList(), - ), - ), - ); - }, + ), + ); + }, + ), + TextFormField( + decoration: InputDecoration( + labelText: AppLocalizations.of(context).notes, ), - TextFormField( - decoration: InputDecoration( - labelText: AppLocalizations.of(context).notes, + maxLines: 3, + controller: notesController, + keyboardType: TextInputType.multiline, + onFieldSubmitted: (_) {}, + onSaved: (newValue) { + _session.notes = newValue; + }, + ), + Row( + children: [ + Flexible( + child: TextFormField( + decoration: + InputDecoration(labelText: AppLocalizations.of(context).timeStart), + controller: timeStartController, + onFieldSubmitted: (_) {}, + onSaved: (newValue) {}, + ), ), - maxLines: 3, - controller: notesController, - keyboardType: TextInputType.multiline, - onFieldSubmitted: (_) {}, - onSaved: (newValue) { - _session.notes = newValue; - }, - ), - Row( - children: [ - Flexible( - child: TextFormField( - decoration: - InputDecoration(labelText: AppLocalizations.of(context).timeStart), - controller: timeStartController, - onFieldSubmitted: (_) {}, - onSaved: (newValue) {}, - ), + Flexible( + child: TextFormField( + decoration: + InputDecoration(labelText: AppLocalizations.of(context).timeEnd), + controller: timeEndController, + onFieldSubmitted: (_) {}, + onSaved: (newValue) {}, ), - Flexible( - child: TextFormField( - decoration: - InputDecoration(labelText: AppLocalizations.of(context).timeEnd), - controller: timeEndController, - onFieldSubmitted: (_) {}, - onSaved: (newValue) {}, - ), - ), - ], - ), - ElevatedButton( - child: Text(AppLocalizations.of(context).save), - onPressed: () async { - // Validate and save the current values to the weightEntry - final isValid = _form.currentState.validate(); - if (!isValid) { - return; - } - _form.currentState.save(); - _session.date = DateTime.now(); - _session.workoutId = widget._workoutPlan.id; - _session.impression = impressionValue; + ), + ], + ), + ElevatedButton( + child: Text(AppLocalizations.of(context).save), + onPressed: () async { + // Validate and save the current values to the weightEntry + final isValid = _form.currentState.validate(); + if (!isValid) { + return; + } + _form.currentState.save(); + _session.date = DateTime.now(); + _session.workoutId = widget._workoutPlan.id; + _session.impression = impressionValue; - // Save the entry on the server - try { - print(_session.toJson()); - await Provider.of(context, listen: false) - .addSession(_session); - Navigator.of(context).pop(); - } on WgerHttpException catch (error) { - showHttpExceptionErrorDialog(error, context); - } catch (error) { - showErrorDialog(error, context); - } - }, - ), - ], - ), + // Save the entry on the server + try { + print(_session.toJson()); + await Provider.of(context, listen: false).addSession(_session); + Navigator.of(context).pop(); + } on WgerHttpException catch (error) { + showHttpExceptionErrorDialog(error, context); + } catch (error) { + showErrorDialog(error, context); + } + }, + ), + ], ), ), IconButton( From 3ffd98e7e3345775b6b628db89ee6fee6b6527e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Thu, 11 Mar 2021 20:47:22 +0000 Subject: [PATCH 07/58] Translated using Weblate (English) Currently translated at 100.0% (52 of 52 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/en/ --- lib/l10n/app_en.arb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 627507f79..aadd57de0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -156,7 +156,7 @@ "@toggleDetails": { "description": "Switch to toggle detail / overview" }, - "aboutText": "wger is copylefted libre software, licensed GPLv3+ and available on GitHub:", + "aboutText": "wger is copylefted libre software, licensed AGPLv3+ and available on GitHub:", "@aboutText": { "description": "Text in the about dialog" } From 0b773fc12a10d3a01669433ba63f274b564e2b7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Thu, 11 Mar 2021 20:47:49 +0000 Subject: [PATCH 08/58] Translated using Weblate (German) Currently translated at 100.0% (52 of 52 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/de/ --- lib/l10n/app_de.arb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index f4693e4a9..1bc4706a8 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -36,7 +36,7 @@ "@toggleDetails": { "description": "Switch to toggle detail / overview" }, - "aboutText": "wger ist copylefted-Software, lizenziert unter der GPLv3+ und verfügbar auf GitHub:", + "aboutText": "wger ist copylefted-Software, lizenziert unter der AGPLv3+ und verfügbar auf GitHub:", "@aboutText": { "description": "Text in the about dialog" }, From d6c714d56f124224d48e2c3a9edcc3990a91edc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Thu, 11 Mar 2021 20:33:30 +0000 Subject: [PATCH 09/58] Translated using Weblate (English) Currently translated at 75.0% (3 of 4 strings) Translation: wger Workout Manager/Play Store Translate-URL: https://hosted.weblate.org/projects/wger/play-store/en/ --- .../fastlane/metadata/android/en-US/full_description.txt | 7 +++++-- .../fastlane/metadata/android/en-US/short_description.txt | 2 +- android/fastlane/metadata/android/en-US/title.txt | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/android/fastlane/metadata/android/en-US/full_description.txt b/android/fastlane/metadata/android/en-US/full_description.txt index 873210aa0..c092a1259 100644 --- a/android/fastlane/metadata/android/en-US/full_description.txt +++ b/android/fastlane/metadata/android/en-US/full_description.txt @@ -1,3 +1,6 @@ -wger (ˈvɛɡɐ) Workout Manager is a free, open source application that helps you manage your personal workouts, weight and diet plans +wger (ˈvɛɡɐ) is copylefted libre software helping your health. -TODO... \ No newline at end of file +- Plan workouts and nutrition +- Save exercises and comment them +- Gym mode +- Diary and tracking of development diff --git a/android/fastlane/metadata/android/en-US/short_description.txt b/android/fastlane/metadata/android/en-US/short_description.txt index 02465a7e7..aa12d8cd0 100644 --- a/android/fastlane/metadata/android/en-US/short_description.txt +++ b/android/fastlane/metadata/android/en-US/short_description.txt @@ -1 +1 @@ -Fitness/workout, nutrition and weight tracker \ No newline at end of file +Fitness/workout, nutrition and weight tracker diff --git a/android/fastlane/metadata/android/en-US/title.txt b/android/fastlane/metadata/android/en-US/title.txt index ea0df9560..d35e40870 100644 --- a/android/fastlane/metadata/android/en-US/title.txt +++ b/android/fastlane/metadata/android/en-US/title.txt @@ -1 +1 @@ -wger Workout Manager \ No newline at end of file +wger Workout Manager From 07ee3492a1b670be26f0f201483da925f8672131 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Thu, 11 Mar 2021 20:34:28 +0000 Subject: [PATCH 10/58] =?UTF-8?q?Translated=20using=20Weblate=20(Norwegian?= =?UTF-8?q?=20Bokm=C3=A5l)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently translated at 100.0% (4 of 4 strings) Translation: wger Workout Manager/Play Store Translate-URL: https://hosted.weblate.org/projects/wger/play-store/nb_NO/ --- .../fastlane/metadata/android/nb-NO/full_description.txt | 6 ++++++ .../fastlane/metadata/android/nb-NO/short_description.txt | 1 + 2 files changed, 7 insertions(+) create mode 100644 android/fastlane/metadata/android/nb-NO/full_description.txt create mode 100644 android/fastlane/metadata/android/nb-NO/short_description.txt diff --git a/android/fastlane/metadata/android/nb-NO/full_description.txt b/android/fastlane/metadata/android/nb-NO/full_description.txt new file mode 100644 index 000000000..e5160aa75 --- /dev/null +++ b/android/fastlane/metadata/android/nb-NO/full_description.txt @@ -0,0 +1,6 @@ +wger (ˈvɛɡɐ) er gemenhetslig fri programvare som hjelper din helse. + +- Planlegg treningsøkter og ernæring +- Lagre øvelser og kommenter dem +- Helsestudio-modus +- Dagbok og utviklingssporing diff --git a/android/fastlane/metadata/android/nb-NO/short_description.txt b/android/fastlane/metadata/android/nb-NO/short_description.txt new file mode 100644 index 000000000..b402172c9 --- /dev/null +++ b/android/fastlane/metadata/android/nb-NO/short_description.txt @@ -0,0 +1 @@ +Fitness/treningsøkt, ernæring og vektlogging From c56911bb1108706d536041e5bb3516e7e3ade877 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 14 Mar 2021 19:27:03 +0100 Subject: [PATCH 11/58] Run flutter create and commit web folder While this application is not meant to be run on the web, it is very useful for testing and developing --- web/favicon.png | Bin 0 -> 917 bytes web/icons/Icon-192.png | Bin 0 -> 5292 bytes web/icons/Icon-512.png | Bin 0 -> 8252 bytes web/index.html | 45 +++++++++++++++++++++++++++++++++++++++++ web/manifest.json | 23 +++++++++++++++++++++ 5 files changed, 68 insertions(+) create mode 100644 web/favicon.png create mode 100644 web/icons/Icon-192.png create mode 100644 web/icons/Icon-512.png create mode 100644 web/index.html create mode 100644 web/manifest.json diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..8aaa46ac1ae21512746f852a42ba87e4165dfdd1 GIT binary patch literal 917 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|I14-?iy0X7 zltGxWVyS%@P(fs7NJL45ua8x7ey(0(N`6wRUPW#JP&EUCO@$SZnVVXYs8ErclUHn2 zVXFjIVFhG^g!Ppaz)DK8ZIvQ?0~DO|i&7O#^-S~(l1AfjnEK zjFOT9D}DX)@^Za$W4-*MbbUihOG|wNBYh(yU7!lx;>x^|#0uTKVr7USFmqf|i<65o z3raHc^AtelCMM;Vme?vOfh>Xph&xL%(-1c06+^uR^q@XSM&D4+Kp$>4P^%3{)XKjo zGZknv$b36P8?Z_gF{nK@`XI}Z90TzwSQO}0J1!f2c(B=V`5aP@1P1a|PZ!4!3&Gl8 zTYqUsf!gYFyJnXpu0!n&N*SYAX-%d(5gVjrHJWqXQshj@!Zm{!01WsQrH~9=kTxW#6SvuapgMqt>$=j#%eyGrQzr zP{L-3gsMA^$I1&gsBAEL+vxi1*Igl=8#8`5?A-T5=z-sk46WA1IUT)AIZHx1rdUrf zVJrJn<74DDw`j)Ki#gt}mIT-Q`XRa2-jQXQoI%w`nb|XblvzK${ZzlV)m-XcwC(od z71_OEC5Bt9GEXosOXaPTYOia#R4ID2TiU~`zVMl08TV_C%DnU4^+HE>9(CE4D6?Fz oujB08i7adh9xk7*FX66dWH6F5TM;?E2b5PlUHx3vIVCg!0Dx9vYXATM literal 0 HcmV?d00001 diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..b749bfef07473333cf1dd31e9eed89862a5d52aa GIT binary patch literal 5292 zcmZ`-2T+sGz6~)*FVZ`aW+(v>MIm&M-g^@e2u-B-DoB?qO+b1Tq<5uCCv>ESfRum& zp%X;f!~1{tzL__3=gjVJ=j=J>+nMj%ncXj1Q(b|Ckbw{Y0FWpt%4y%$uD=Z*c-x~o zE;IoE;xa#7Ll5nj-e4CuXB&G*IM~D21rCP$*xLXAK8rIMCSHuSu%bL&S3)8YI~vyp@KBu9Ph7R_pvKQ@xv>NQ`dZp(u{Z8K3yOB zn7-AR+d2JkW)KiGx0hosml;+eCXp6+w%@STjFY*CJ?udJ64&{BCbuebcuH;}(($@@ znNlgBA@ZXB)mcl9nbX#F!f_5Z=W>0kh|UVWnf!At4V*LQP%*gPdCXd6P@J4Td;!Ur z<2ZLmwr(NG`u#gDEMP19UcSzRTL@HsK+PnIXbVBT@oHm53DZr?~V(0{rsalAfwgo zEh=GviaqkF;}F_5-yA!1u3!gxaR&Mj)hLuj5Q-N-@Lra{%<4ONja8pycD90&>yMB` zchhd>0CsH`^|&TstH-8+R`CfoWqmTTF_0?zDOY`E`b)cVi!$4xA@oO;SyOjJyP^_j zx^@Gdf+w|FW@DMdOi8=4+LJl$#@R&&=UM`)G!y%6ZzQLoSL%*KE8IO0~&5XYR9 z&N)?goEiWA(YoRfT{06&D6Yuu@Qt&XVbuW@COb;>SP9~aRc+z`m`80pB2o%`#{xD@ zI3RAlukL5L>px6b?QW1Ac_0>ew%NM!XB2(H+1Y3AJC?C?O`GGs`331Nd4ZvG~bMo{lh~GeL zSL|tT*fF-HXxXYtfu5z+T5Mx9OdP7J4g%@oeC2FaWO1D{=NvL|DNZ}GO?O3`+H*SI z=grGv=7dL{+oY0eJFGO!Qe(e2F?CHW(i!!XkGo2tUvsQ)I9ev`H&=;`N%Z{L zO?vV%rDv$y(@1Yj@xfr7Kzr<~0{^T8wM80xf7IGQF_S-2c0)0D6b0~yD7BsCy+(zL z#N~%&e4iAwi4F$&dI7x6cE|B{f@lY5epaDh=2-(4N05VO~A zQT3hanGy_&p+7Fb^I#ewGsjyCEUmSCaP6JDB*=_()FgQ(-pZ28-{qx~2foO4%pM9e z*_63RT8XjgiaWY|*xydf;8MKLd{HnfZ2kM%iq}fstImB-K6A79B~YoPVa@tYN@T_$ zea+9)<%?=Fl!kd(Y!G(-o}ko28hg2!MR-o5BEa_72uj7Mrc&{lRh3u2%Y=Xk9^-qa zBPWaD=2qcuJ&@Tf6ue&)4_V*45=zWk@Z}Q?f5)*z)-+E|-yC4fs5CE6L_PH3=zI8p z*Z3!it{1e5_^(sF*v=0{`U9C741&lub89gdhKp|Y8CeC{_{wYK-LSbp{h)b~9^j!s z7e?Y{Z3pZv0J)(VL=g>l;<}xk=T*O5YR|hg0eg4u98f2IrA-MY+StQIuK-(*J6TRR z|IM(%uI~?`wsfyO6Tgmsy1b3a)j6M&-jgUjVg+mP*oTKdHg?5E`!r`7AE_#?Fc)&a z08KCq>Gc=ne{PCbRvs6gVW|tKdcE1#7C4e`M|j$C5EYZ~Y=jUtc zj`+?p4ba3uy7><7wIokM79jPza``{Lx0)zGWg;FW1^NKY+GpEi=rHJ+fVRGfXO zPHV52k?jxei_!YYAw1HIz}y8ZMwdZqU%ESwMn7~t zdI5%B;U7RF=jzRz^NuY9nM)&<%M>x>0(e$GpU9th%rHiZsIT>_qp%V~ILlyt^V`=d z!1+DX@ah?RnB$X!0xpTA0}lN@9V-ePx>wQ?-xrJr^qDlw?#O(RsXeAvM%}rg0NT#t z!CsT;-vB=B87ShG`GwO;OEbeL;a}LIu=&@9cb~Rsx(ZPNQ!NT7H{@j0e(DiLea>QD zPmpe90gEKHEZ8oQ@6%E7k-Ptn#z)b9NbD@_GTxEhbS+}Bb74WUaRy{w;E|MgDAvHw zL)ycgM7mB?XVh^OzbC?LKFMotw3r@i&VdUV%^Efdib)3@soX%vWCbnOyt@Y4swW925@bt45y0HY3YI~BnnzZYrinFy;L?2D3BAL`UQ zEj))+f>H7~g8*VuWQ83EtGcx`hun$QvuurSMg3l4IP8Fe`#C|N6mbYJ=n;+}EQm;< z!!N=5j1aAr_uEnnzrEV%_E|JpTb#1p1*}5!Ce!R@d$EtMR~%9# zd;h8=QGT)KMW2IKu_fA_>p_und#-;Q)p%%l0XZOXQicfX8M~7?8}@U^ihu;mizj)t zgV7wk%n-UOb z#!P5q?Ex+*Kx@*p`o$q8FWL*E^$&1*!gpv?Za$YO~{BHeGY*5%4HXUKa_A~~^d z=E*gf6&+LFF^`j4$T~dR)%{I)T?>@Ma?D!gi9I^HqvjPc3-v~=qpX1Mne@*rzT&Xw zQ9DXsSV@PqpEJO-g4A&L{F&;K6W60D!_vs?Vx!?w27XbEuJJP&);)^+VF1nHqHBWu z^>kI$M9yfOY8~|hZ9WB!q-9u&mKhEcRjlf2nm_@s;0D#c|@ED7NZE% zzR;>P5B{o4fzlfsn3CkBK&`OSb-YNrqx@N#4CK!>bQ(V(D#9|l!e9(%sz~PYk@8zt zPN9oK78&-IL_F zhsk1$6p;GqFbtB^ZHHP+cjMvA0(LqlskbdYE_rda>gvQLTiqOQ1~*7lg%z*&p`Ry& zRcG^DbbPj_jOKHTr8uk^15Boj6>hA2S-QY(W-6!FIq8h$<>MI>PYYRenQDBamO#Fv zAH5&ImqKBDn0v5kb|8i0wFhUBJTpT!rB-`zK)^SNnRmLraZcPYK7b{I@+}wXVdW-{Ps17qdRA3JatEd?rPV z4@}(DAMf5EqXCr4-B+~H1P#;t@O}B)tIJ(W6$LrK&0plTmnPpb1TKn3?f?Kk``?D+ zQ!MFqOX7JbsXfQrz`-M@hq7xlfNz;_B{^wbpG8des56x(Q)H)5eLeDwCrVR}hzr~= zM{yXR6IM?kXxauLza#@#u?Y|o;904HCqF<8yT~~c-xyRc0-vxofnxG^(x%>bj5r}N zyFT+xnn-?B`ohA>{+ZZQem=*Xpqz{=j8i2TAC#x-m;;mo{{sLB_z(UoAqD=A#*juZ zCv=J~i*O8;F}A^Wf#+zx;~3B{57xtoxC&j^ie^?**T`WT2OPRtC`xj~+3Kprn=rVM zVJ|h5ux%S{dO}!mq93}P+h36mZ5aZg1-?vhL$ke1d52qIiXSE(llCr5i=QUS?LIjc zV$4q=-)aaR4wsrQv}^shL5u%6;`uiSEs<1nG^?$kl$^6DL z43CjY`M*p}ew}}3rXc7Xck@k41jx}c;NgEIhKZ*jsBRZUP-x2cm;F1<5$jefl|ppO zmZd%%?gMJ^g9=RZ^#8Mf5aWNVhjAS^|DQO+q$)oeob_&ZLFL(zur$)); zU19yRm)z<4&4-M}7!9+^Wl}Uk?`S$#V2%pQ*SIH5KI-mn%i;Z7-)m$mN9CnI$G7?# zo`zVrUwoSL&_dJ92YhX5TKqaRkfPgC4=Q&=K+;_aDs&OU0&{WFH}kKX6uNQC6%oUH z2DZa1s3%Vtk|bglbxep-w)PbFG!J17`<$g8lVhqD2w;Z0zGsh-r zxZ13G$G<48leNqR!DCVt9)@}(zMI5w6Wo=N zpP1*3DI;~h2WDWgcKn*f!+ORD)f$DZFwgKBafEZmeXQMAsq9sxP9A)7zOYnkHT9JU zRA`umgmP9d6=PHmFIgx=0$(sjb>+0CHG)K@cPG{IxaJ&Ueo8)0RWgV9+gO7+Bl1(F z7!BslJ2MP*PWJ;x)QXbR$6jEr5q3 z(3}F@YO_P1NyTdEXRLU6fp?9V2-S=E+YaeLL{Y)W%6`k7$(EW8EZSA*(+;e5@jgD^I zaJQ2|oCM1n!A&-8`;#RDcZyk*+RPkn_r8?Ak@agHiSp*qFNX)&i21HE?yuZ;-C<3C zwJGd1lx5UzViP7sZJ&|LqH*mryb}y|%AOw+v)yc`qM)03qyyrqhX?ub`Cjwx2PrR! z)_z>5*!*$x1=Qa-0uE7jy0z`>|Ni#X+uV|%_81F7)b+nf%iz=`fF4g5UfHS_?PHbr zB;0$bK@=di?f`dS(j{l3-tSCfp~zUuva+=EWxJcRfp(<$@vd(GigM&~vaYZ0c#BTs z3ijkxMl=vw5AS&DcXQ%eeKt!uKvh2l3W?&3=dBHU=Gz?O!40S&&~ei2vg**c$o;i89~6DVns zG>9a*`k5)NI9|?W!@9>rzJ;9EJ=YlJTx1r1BA?H`LWijk(rTax9(OAu;q4_wTj-yj z1%W4GW&K4T=uEGb+E!>W0SD_C0RR91 literal 0 HcmV?d00001 diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..88cfd48dff1169879ba46840804b412fe02fefd6 GIT binary patch literal 8252 zcmd5=2T+s!lYZ%-(h(2@5fr2dC?F^$C=i-}R6$UX8af(!je;W5yC_|HmujSgN*6?W z3knF*TL1$|?oD*=zPbBVex*RUIKsL<(&Rj9%^UD2IK3W?2j>D?eWQgvS-HLymHo9%~|N2Q{~j za?*X-{b9JRowv_*Mh|;*-kPFn>PI;r<#kFaxFqbn?aq|PduQg=2Q;~Qc}#z)_T%x9 zE|0!a70`58wjREmAH38H1)#gof)U3g9FZ^ zF7&-0^Hy{4XHWLoC*hOG(dg~2g6&?-wqcpf{ z&3=o8vw7lMi22jCG9RQbv8H}`+}9^zSk`nlR8?Z&G2dlDy$4#+WOlg;VHqzuE=fM@ z?OI6HEJH4&tA?FVG}9>jAnq_^tlw8NbjNhfqk2rQr?h(F&WiKy03Sn=-;ZJRh~JrD zbt)zLbnabttEZ>zUiu`N*u4sfQaLE8-WDn@tHp50uD(^r-}UsUUu)`!Rl1PozAc!a z?uj|2QDQ%oV-jxUJmJycySBINSKdX{kDYRS=+`HgR2GO19fg&lZKyBFbbXhQV~v~L za^U944F1_GtuFXtvDdDNDvp<`fqy);>Vw=ncy!NB85Tw{&sT5&Ox%-p%8fTS;OzlRBwErvO+ROe?{%q-Zge=%Up|D4L#>4K@Ke=x%?*^_^P*KD zgXueMiS63!sEw@fNLB-i^F|@Oib+S4bcy{eu&e}Xvb^(mA!=U=Xr3||IpV~3K zQWzEsUeX_qBe6fky#M zzOJm5b+l;~>=sdp%i}}0h zO?B?i*W;Ndn02Y0GUUPxERG`3Bjtj!NroLoYtyVdLtl?SE*CYpf4|_${ku2s`*_)k zN=a}V8_2R5QANlxsq!1BkT6$4>9=-Ix4As@FSS;1q^#TXPrBsw>hJ}$jZ{kUHoP+H zvoYiR39gX}2OHIBYCa~6ERRPJ#V}RIIZakUmuIoLF*{sO8rAUEB9|+A#C|@kw5>u0 zBd=F!4I)Be8ycH*)X1-VPiZ+Ts8_GB;YW&ZFFUo|Sw|x~ZajLsp+_3gv((Q#N>?Jz zFBf`~p_#^${zhPIIJY~yo!7$-xi2LK%3&RkFg}Ax)3+dFCjGgKv^1;lUzQlPo^E{K zmCnrwJ)NuSaJEmueEPO@(_6h3f5mFffhkU9r8A8(JC5eOkux{gPmx_$Uv&|hyj)gN zd>JP8l2U&81@1Hc>#*su2xd{)T`Yw< zN$dSLUN}dfx)Fu`NcY}TuZ)SdviT{JHaiYgP4~@`x{&h*Hd>c3K_To9BnQi@;tuoL z%PYQo&{|IsM)_>BrF1oB~+`2_uZQ48z9!)mtUR zdfKE+b*w8cPu;F6RYJiYyV;PRBbThqHBEu_(U{(gGtjM}Zi$pL8Whx}<JwE3RM0F8x7%!!s)UJVq|TVd#hf1zVLya$;mYp(^oZQ2>=ZXU1c$}f zm|7kfk>=4KoQoQ!2&SOW5|JP1)%#55C$M(u4%SP~tHa&M+=;YsW=v(Old9L3(j)`u z2?#fK&1vtS?G6aOt@E`gZ9*qCmyvc>Ma@Q8^I4y~f3gs7*d=ATlP>1S zyF=k&6p2;7dn^8?+!wZO5r~B+;@KXFEn^&C=6ma1J7Au6y29iMIxd7#iW%=iUzq&C=$aPLa^Q zncia$@TIy6UT@69=nbty5epP>*fVW@5qbUcb2~Gg75dNd{COFLdiz3}kODn^U*=@E z0*$7u7Rl2u)=%fk4m8EK1ctR!6%Ve`e!O20L$0LkM#f+)n9h^dn{n`T*^~d+l*Qlx z$;JC0P9+en2Wlxjwq#z^a6pdnD6fJM!GV7_%8%c)kc5LZs_G^qvw)&J#6WSp< zmsd~1-(GrgjC56Pdf6#!dt^y8Rg}!#UXf)W%~PeU+kU`FeSZHk)%sFv++#Dujk-~m zFHvVJC}UBn2jN& zs!@nZ?e(iyZPNo`p1i#~wsv9l@#Z|ag3JR>0#u1iW9M1RK1iF6-RbJ4KYg?B`dET9 zyR~DjZ>%_vWYm*Z9_+^~hJ_|SNTzBKx=U0l9 z9x(J96b{`R)UVQ$I`wTJ@$_}`)_DyUNOso6=WOmQKI1e`oyYy1C&%AQU<0-`(ow)1 zT}gYdwWdm4wW6|K)LcfMe&psE0XGhMy&xS`@vLi|1#Za{D6l@#D!?nW87wcscUZgELT{Cz**^;Zb~7 z(~WFRO`~!WvyZAW-8v!6n&j*PLm9NlN}BuUN}@E^TX*4Or#dMMF?V9KBeLSiLO4?B zcE3WNIa-H{ThrlCoN=XjOGk1dT=xwwrmt<1a)mrRzg{35`@C!T?&_;Q4Ce=5=>z^*zE_c(0*vWo2_#TD<2)pLXV$FlwP}Ik74IdDQU@yhkCr5h zn5aa>B7PWy5NQ!vf7@p_qtC*{dZ8zLS;JetPkHi>IvPjtJ#ThGQD|Lq#@vE2xdl%`x4A8xOln}BiQ92Po zW;0%A?I5CQ_O`@Ad=`2BLPPbBuPUp@Hb%a_OOI}y{Rwa<#h z5^6M}s7VzE)2&I*33pA>e71d78QpF>sNK;?lj^Kl#wU7G++`N_oL4QPd-iPqBhhs| z(uVM}$ItF-onXuuXO}o$t)emBO3Hjfyil@*+GF;9j?`&67GBM;TGkLHi>@)rkS4Nj zAEk;u)`jc4C$qN6WV2dVd#q}2X6nKt&X*}I@jP%Srs%%DS92lpDY^K*Sx4`l;aql$ zt*-V{U&$DM>pdO?%jt$t=vg5|p+Rw?SPaLW zB6nvZ69$ne4Z(s$3=Rf&RX8L9PWMV*S0@R zuIk&ba#s6sxVZ51^4Kon46X^9`?DC9mEhWB3f+o4#2EXFqy0(UTc>GU| zGCJmI|Dn-dX#7|_6(fT)>&YQ0H&&JX3cTvAq(a@ydM4>5Njnuere{J8p;3?1az60* z$1E7Yyxt^ytULeokgDnRVKQw9vzHg1>X@@jM$n$HBlveIrKP5-GJq%iWH#odVwV6cF^kKX(@#%%uQVb>#T6L^mC@)%SMd4DF? zVky!~ge27>cpUP1Vi}Z32lbLV+CQy+T5Wdmva6Fg^lKb!zrg|HPU=5Qu}k;4GVH+x z%;&pN1LOce0w@9i1Mo-Y|7|z}fbch@BPp2{&R-5{GLoeu8@limQmFF zaJRR|^;kW_nw~0V^ zfTnR!Ni*;-%oSHG1yItARs~uxra|O?YJxBzLjpeE-=~TO3Dn`JL5Gz;F~O1u3|FE- zvK2Vve`ylc`a}G`gpHg58Cqc9fMoy1L}7x7T>%~b&irrNMo?np3`q;d3d;zTK>nrK zOjPS{@&74-fA7j)8uT9~*g23uGnxwIVj9HorzUX#s0pcp2?GH6i}~+kv9fWChtPa_ z@T3m+$0pbjdQw7jcnHn;Pi85hk_u2-1^}c)LNvjdam8K-XJ+KgKQ%!?2n_!#{$H|| zLO=%;hRo6EDmnOBKCL9Cg~ETU##@u^W_5joZ%Et%X_n##%JDOcsO=0VL|Lkk!VdRJ z^|~2pB@PUspT?NOeO?=0Vb+fAGc!j%Ufn-cB`s2A~W{Zj{`wqWq_-w0wr@6VrM zbzni@8c>WS!7c&|ZR$cQ;`niRw{4kG#e z70e!uX8VmP23SuJ*)#(&R=;SxGAvq|&>geL&!5Z7@0Z(No*W561n#u$Uc`f9pD70# z=sKOSK|bF~#khTTn)B28h^a1{;>EaRnHj~>i=Fnr3+Fa4 z`^+O5_itS#7kPd20rq66_wH`%?HNzWk@XFK0n;Z@Cx{kx==2L22zWH$Yg?7 zvDj|u{{+NR3JvUH({;b*$b(U5U z7(lF!1bz2%06+|-v(D?2KgwNw7( zJB#Tz+ZRi&U$i?f34m7>uTzO#+E5cbaiQ&L}UxyOQq~afbNB4EI{E04ZWg53w0A{O%qo=lF8d zf~ktGvIgf-a~zQoWf>loF7pOodrd0a2|BzwwPDV}ShauTK8*fmF6NRbO>Iw9zZU}u zw8Ya}?seBnEGQDmH#XpUUkj}N49tP<2jYwTFp!P+&Fd(%Z#yo80|5@zN(D{_pNow*&4%ql zW~&yp@scb-+Qj-EmErY+Tu=dUmf@*BoXY2&oKT8U?8?s1d}4a`Aq>7SV800m$FE~? zjmz(LY+Xx9sDX$;vU`xgw*jLw7dWOnWWCO8o|;}f>cu0Q&`0I{YudMn;P;L3R-uz# zfns_mZED_IakFBPP2r_S8XM$X)@O-xVKi4`7373Jkd5{2$M#%cRhWer3M(vr{S6>h zj{givZJ3(`yFL@``(afn&~iNx@B1|-qfYiZu?-_&Z8+R~v`d6R-}EX9IVXWO-!hL5 z*k6T#^2zAXdardU3Ao~I)4DGdAv2bx{4nOK`20rJo>rmk3S2ZDu}))8Z1m}CKigf0 z3L`3Y`{huj`xj9@`$xTZzZc3je?n^yG<8sw$`Y%}9mUsjUR%T!?k^(q)6FH6Af^b6 zlPg~IEwg0y;`t9y;#D+uz!oE4VP&Je!<#q*F?m5L5?J3i@!0J6q#eu z!RRU`-)HeqGi_UJZ(n~|PSNsv+Wgl{P-TvaUQ9j?ZCtvb^37U$sFpBrkT{7Jpd?HpIvj2!}RIq zH{9~+gErN2+}J`>Jvng2hwM`=PLNkc7pkjblKW|+Fk9rc)G1R>Ww>RC=r-|!m-u7( zc(a$9NG}w#PjWNMS~)o=i~WA&4L(YIW25@AL9+H9!?3Y}sv#MOdY{bb9j>p`{?O(P zIvb`n?_(gP2w3P#&91JX*md+bBEr%xUHMVqfB;(f?OPtMnAZ#rm5q5mh;a2f_si2_ z3oXWB?{NF(JtkAn6F(O{z@b76OIqMC$&oJ_&S|YbFJ*)3qVX_uNf5b8(!vGX19hsG z(OP>RmZp29KH9Ge2kKjKigUmOe^K_!UXP`von)PR8Qz$%=EmOB9xS(ZxE_tnyzo}7 z=6~$~9k0M~v}`w={AeqF?_)9q{m8K#6M{a&(;u;O41j)I$^T?lx5(zlebpY@NT&#N zR+1bB)-1-xj}R8uwqwf=iP1GbxBjneCC%UrSdSxK1vM^i9;bUkS#iRZw2H>rS<2<$ zNT3|sDH>{tXb=zq7XZi*K?#Zsa1h1{h5!Tq_YbKFm_*=A5-<~j63he;4`77!|LBlo zR^~tR3yxcU=gDFbshyF6>o0bdp$qmHS7D}m3;^QZq9kBBU|9$N-~oU?G5;jyFR7>z hN`IR97YZXIo@y!QgFWddJ3|0`sjFx!m))><{BI=FK%f8s literal 0 HcmV?d00001 diff --git a/web/index.html b/web/index.html new file mode 100644 index 000000000..d1cd06795 --- /dev/null +++ b/web/index.html @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + wger + + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 000000000..0e3090fe1 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,23 @@ +{ + "name": "wger", + "short_name": "wger", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + } + ] +} From 8c710fb2b0efd59e7326b12e435a9935751d1967 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 14 Mar 2021 22:56:24 +0100 Subject: [PATCH 12/58] Allow using a custom wger instance for login --- lib/l10n/app_en.arb | 54 +++++++++++++++++ lib/providers/auth.dart | 19 +++++- lib/screens/auth_screen.dart | 113 +++++++++++++++++++++++++++-------- pubspec.lock | 8 +-- 4 files changed, 163 insertions(+), 31 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 663ef66b5..d59b593d2 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1,5 +1,59 @@ { "@@last_modified": "2020-11-11T15:04:05.523531", + "login": "Login", + "@login": { + "description": "Text for login button" + }, + "register": "Register", + "@register": { + "description": "Text for registration button" + }, + "useDefaultServer": "Use default server", + "@useDefaultServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "useCustomServer": "Use custom server", + "@useCustomServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "invalidUrl": "Please enter a valid URL", + "@invalidUrl": { + "description": "Error message when the user enters an invalid URL, e.g. in the login form" + }, + "passwordsDontMatch": "The passwords don't match", + "@passwordsDontMatch": { + "description": "Error message when the user enters two different passwords during registration" + }, + "passwordTooShort": "The password is too short", + "@passwordTooShort": { + "description": "Error message when the user a password that is too short" + }, + "password": "Password", + "confirmPassword": "Confirm password", + "invalidEmail": "Please enter a valid email address", + "@invalidEmail": { + "description": "Error message when the user enters an invalid email" + }, + "email": "Email", + "username": "Username", + "invalidUsername": "Please enter a valid username", + "@invalidUsername": { + "description": "Error message when the user enters an invalid username" + }, + "customServerUrl": "URL of the wger instance", + "@customServerUrl": { + "description": "Label in the form where the users can enter their own wger instance" + }, + "customServerHint": "Enter the the address of your own server, otherwise the default one will be used", + "@customServerHint": { + "description": "Hint text for the form where the users can enter their own wger instance" + }, + "reset": "Reset", + "@reset": { + "description": "Button text allowing the user to reset the entered values to the default" + }, + "registerInstead": "Register instead", + "loginInstead": "Login instead", "labelWorkoutPlans": "Workout plans", "@labelWorkoutPlans": { "description": "Title for screen workout plans" diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index 27e936cd3..73389dae7 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -32,6 +32,8 @@ import 'package:wger/models/http_exception.dart'; import 'helpers.dart'; +final DEFAULT_SERVER = 'https://wger.rge.uber.space'; + class Auth with ChangeNotifier { String token; String serverUrl; @@ -115,7 +117,7 @@ class Auth with ChangeNotifier { /// Authenticates a user Future login(String username, String password, String serverUrl) async { - final uri = Uri.http(serverUrl, '/api/v2/login/'); + final uri = Uri.parse(serverUrl + '/api/v2/login/'); await logout(); try { @@ -152,15 +154,30 @@ class Auth with ChangeNotifier { 'serverUrl': this.serverUrl, // 'expiryDate': _expiryDate.toIso8601String(), }); + final serverData = json.encode({ + 'serverUrl': this.serverUrl, + }); await setServerVersion(); await setApplicationVersion(); prefs.setString('userData', userData); + prefs.setString('lastServer', serverData); } catch (error) { throw error; } } + /// Loads the last server URL from which the user successfully logged in + Future getServerUrlFromPrefs() async { + final prefs = await SharedPreferences.getInstance(); + if (!prefs.containsKey('lastServer')) { + return DEFAULT_SERVER; + } + + final userData = json.decode(prefs.getString('lastServer')) as Map; + return userData['serverUrl']; + } + Future tryAutoLogin() async { final prefs = await SharedPreferences.getInstance(); if (!prefs.containsKey('userData')) { diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index 69da28786..44d9d5747 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:wger/helpers/ui.dart'; import 'package:wger/models/http_exception.dart'; @@ -93,6 +94,7 @@ class AuthCard extends StatefulWidget { class _AuthCardState extends State { final GlobalKey _formKey = GlobalKey(); AuthMode _authMode = AuthMode.Login; + bool _hideCustomServer = true; Map _authData = { 'username': '', 'email': '', @@ -104,7 +106,16 @@ class _AuthCardState extends State { final _passwordController = TextEditingController(text: 'adminadmin'); final _password2Controller = TextEditingController(); final _emailController = TextEditingController(); - final _serverUrlController = TextEditingController(text: 'http://10.0.2.2:8000'); + final _serverUrlController = TextEditingController(text: DEFAULT_SERVER); + + @override + void initState() { + //_serverUrlController.text + super.initState(); + Provider.of(context, listen: false).getServerUrlFromPrefs().then((value) { + _serverUrlController.text = value; + }); + } void _submit(BuildContext context) async { if (!_formKey.currentState.validate()) { @@ -178,14 +189,14 @@ class _AuthCardState extends State { children: [ TextFormField( key: Key('inputUsername'), - decoration: InputDecoration(labelText: 'Username'), + decoration: InputDecoration(labelText: AppLocalizations.of(context).username), autofillHints: [AutofillHints.username], controller: _usernameController, textInputAction: TextInputAction.next, keyboardType: TextInputType.emailAddress, validator: (value) { if (value.isEmpty) { - return 'Invalid Username!'; + return AppLocalizations.of(context).invalidUsername; } return null; }, @@ -196,7 +207,7 @@ class _AuthCardState extends State { if (_authMode == AuthMode.Signup) TextFormField( key: Key('inputEmail'), - decoration: InputDecoration(labelText: 'E-Mail'), + decoration: InputDecoration(labelText: AppLocalizations.of(context).email), autofillHints: [AutofillHints.email], controller: _emailController, keyboardType: TextInputType.emailAddress, @@ -205,7 +216,7 @@ class _AuthCardState extends State { // Email is not required validator: (value) { if (value.isNotEmpty && !value.contains('@')) { - return 'Invalid email!'; + return AppLocalizations.of(context).invalidEmail; } return null; }, @@ -215,17 +226,15 @@ class _AuthCardState extends State { ), TextFormField( key: Key('inputPassword'), - decoration: InputDecoration(labelText: 'Password'), + decoration: InputDecoration(labelText: AppLocalizations.of(context).password), autofillHints: [AutofillHints.password], obscureText: true, controller: _passwordController, textInputAction: TextInputAction.next, validator: (value) { - /* if (value.isEmpty || value.length < 8) { - return 'Password is too short!'; + return AppLocalizations.of(context).passwordTooShort; } - */ return null; }, onSaved: (value) { @@ -235,32 +244,67 @@ class _AuthCardState extends State { if (_authMode == AuthMode.Signup) TextFormField( key: Key('inputPassword2'), - decoration: InputDecoration(labelText: 'Confirm Password'), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).confirmPassword), controller: _password2Controller, enabled: _authMode == AuthMode.Signup, obscureText: true, validator: _authMode == AuthMode.Signup ? (value) { if (value != _passwordController.text) { - return 'Passwords do not match!'; + return AppLocalizations.of(context).passwordsDontMatch; } return null; } : null, ), - TextFormField( - key: Key('inputServer'), - decoration: InputDecoration(labelText: 'Server URL'), - controller: _serverUrlController, - validator: (value) { - if (value.isEmpty || !value.contains('http')) { - return 'Invalid URL!'; - } - return null; - }, - onSaved: (value) { - _authData['serverUrl'] = value; - }, + // Off-stage widgets are kept in the tree, otherwise the server URL + // would not be saved to _authData + Offstage( + offstage: _hideCustomServer, + child: Row( + children: [ + Flexible( + flex: 3, + child: TextFormField( + key: Key('inputServer'), + decoration: InputDecoration( + labelText: AppLocalizations.of(context).customServerUrl, + helperText: AppLocalizations.of(context).customServerHint, + helperMaxLines: 4), + controller: _serverUrlController, + validator: (value) { + if (Uri.tryParse(value) == null) { + return AppLocalizations.of(context).invalidUrl; + } + + if (value.isEmpty || !value.contains('http')) { + return AppLocalizations.of(context).invalidUrl; + } + return null; + }, + onSaved: (value) { + _authData['serverUrl'] = value; + }, + ), + ), + SizedBox( + width: 20, + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.undo), + onPressed: () { + _serverUrlController.text = DEFAULT_SERVER; + }, + ), + Text(AppLocalizations.of(context).reset) + ], + ), + ], + ), ), SizedBox( height: 20, @@ -270,16 +314,33 @@ class _AuthCardState extends State { else ElevatedButton( key: Key('actionButton'), - child: Text(_authMode == AuthMode.Login ? 'LOGIN' : 'REGISTER'), + child: Text(_authMode == AuthMode.Login + ? AppLocalizations.of(context).login + : AppLocalizations.of(context).register), onPressed: () { return _submit(context); }, ), TextButton( key: Key('toggleActionButton'), - child: Text('${_authMode == AuthMode.Login ? 'REGISTER' : 'LOGIN'} INSTEAD'), + child: Text( + _authMode == AuthMode.Login + ? AppLocalizations.of(context).registerInstead.toUpperCase() + : AppLocalizations.of(context).loginInstead.toUpperCase(), + ), onPressed: _switchAuthMode, ), + TextButton( + child: Text(_hideCustomServer + ? AppLocalizations.of(context).useCustomServer + : AppLocalizations.of(context).useDefaultServer), + key: Key('toggleCustomServerButton'), + onPressed: () { + setState(() { + _hideCustomServer = !_hideCustomServer; + }); + }, + ), ], ), ), diff --git a/pubspec.lock b/pubspec.lock index 6981f48bd..505caa441 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -70,7 +70,7 @@ packages: name: build_daemon url: "https://pub.dartlang.org" source: hosted - version: "2.1.9" + version: "2.1.10" build_resolvers: dependency: transitive description: @@ -398,7 +398,7 @@ packages: name: mockito url: "https://pub.dartlang.org" source: hosted - version: "5.0.0" + version: "5.0.1" nested: dependency: transitive description: @@ -725,7 +725,7 @@ packages: name: win32 url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "2.0.4" xdg_directories: dependency: transitive description: @@ -748,5 +748,5 @@ packages: source: hosted version: "3.1.0" sdks: - dart: ">=2.12.0-259.9.beta <3.0.0" + dart: ">=2.12.0 <3.0.0" flutter: ">=1.22.0" From 7c9ccceff48e6d781eaa38fbd779449c30ab738d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 15 Mar 2021 11:04:52 +0100 Subject: [PATCH 13/58] Rename de to de-DE It seems the playstore *only* understands locales with a sub-locale --- .../fastlane/metadata/android/{de => de-DE}/full_description.txt | 0 .../metadata/android/{de => de-DE}/short_description.txt | 0 android/fastlane/metadata/android/de-DE/title.txt | 1 + 3 files changed, 1 insertion(+) rename android/fastlane/metadata/android/{de => de-DE}/full_description.txt (100%) rename android/fastlane/metadata/android/{de => de-DE}/short_description.txt (100%) create mode 100644 android/fastlane/metadata/android/de-DE/title.txt diff --git a/android/fastlane/metadata/android/de/full_description.txt b/android/fastlane/metadata/android/de-DE/full_description.txt similarity index 100% rename from android/fastlane/metadata/android/de/full_description.txt rename to android/fastlane/metadata/android/de-DE/full_description.txt diff --git a/android/fastlane/metadata/android/de/short_description.txt b/android/fastlane/metadata/android/de-DE/short_description.txt similarity index 100% rename from android/fastlane/metadata/android/de/short_description.txt rename to android/fastlane/metadata/android/de-DE/short_description.txt diff --git a/android/fastlane/metadata/android/de-DE/title.txt b/android/fastlane/metadata/android/de-DE/title.txt new file mode 100644 index 000000000..d35e40870 --- /dev/null +++ b/android/fastlane/metadata/android/de-DE/title.txt @@ -0,0 +1 @@ +wger Workout Manager From 3fb2bc5daf2c33e98d45b43085ed9d3928e3efb9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 15 Mar 2021 11:06:25 +0100 Subject: [PATCH 14/58] Update fastfile configuration to allow updating the alpha track --- Gemfile.lock | 34 +++++++++---------- android/fastlane/Fastfile | 16 +++++++++ android/fastlane/README.md | 5 +++ .../fastlane/metadata/android/nb-NO/title.txt | 1 + android/fastlane/report.xml | 6 ++-- pubspec.yaml | 2 +- 6 files changed, 42 insertions(+), 22 deletions(-) create mode 100644 android/fastlane/metadata/android/nb-NO/title.txt diff --git a/Gemfile.lock b/Gemfile.lock index ecb7fde6d..a4c797786 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -6,21 +6,21 @@ GEM public_suffix (>= 2.0.2, < 5.0) artifactory (3.0.15) atomos (0.1.3) - aws-eventstream (1.1.0) - aws-partitions (1.429.0) - aws-sdk-core (3.112.0) + aws-eventstream (1.1.1) + aws-partitions (1.432.0) + aws-sdk-core (3.113.0) aws-eventstream (~> 1, >= 1.0.2) aws-partitions (~> 1, >= 1.239.0) aws-sigv4 (~> 1.1) jmespath (~> 1.0) - aws-sdk-kms (1.42.0) + aws-sdk-kms (1.43.0) aws-sdk-core (~> 3, >= 3.112.0) aws-sigv4 (~> 1.1) - aws-sdk-s3 (1.89.0) + aws-sdk-s3 (1.91.0) aws-sdk-core (~> 3, >= 3.112.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.1) - aws-sigv4 (1.2.2) + aws-sigv4 (1.2.3) aws-eventstream (~> 1, >= 1.0.2) babosa (1.0.4) claide (1.0.3) @@ -47,8 +47,8 @@ GEM faraday-net_http (1.0.1) faraday_middleware (1.0.0) faraday (~> 1.0) - fastimage (2.2.2) - fastlane (2.176.0) + fastimage (2.2.3) + fastlane (2.178.0) CFPropertyList (>= 2.3, < 4.0.0) addressable (>= 2.3, < 3.0.0) artifactory (~> 3.0) @@ -95,7 +95,7 @@ GEM representable (~> 3.0) retriable (>= 2.0, < 4.0) signet (~> 0.12) - google-apis-core (0.2.1) + google-apis-core (0.3.0) addressable (~> 2.5, >= 2.5.1) googleauth (~> 0.14) httpclient (>= 2.8.1, < 3.0) @@ -105,17 +105,17 @@ GEM rexml signet (~> 0.14) webrick - google-apis-iamcredentials_v1 (0.1.0) + google-apis-iamcredentials_v1 (0.2.0) google-apis-core (~> 0.1) - google-apis-storage_v1 (0.2.0) + google-apis-storage_v1 (0.3.0) google-apis-core (~> 0.1) - google-cloud-core (1.5.0) + google-cloud-core (1.6.0) google-cloud-env (~> 1.0) google-cloud-errors (~> 1.0) - google-cloud-env (1.4.0) + google-cloud-env (1.5.0) faraday (>= 0.17.3, < 2.0) - google-cloud-errors (1.0.1) - google-cloud-storage (1.30.0) + google-cloud-errors (1.1.0) + google-cloud-storage (1.31.0) addressable (~> 2.5) digest-crc (~> 0.4) google-apis-iamcredentials_v1 (~> 0.1) @@ -123,7 +123,7 @@ GEM google-cloud-core (~> 1.2) googleauth (~> 0.9) mini_mime (~> 1.0) - googleauth (0.15.1) + googleauth (0.16.0) faraday (>= 0.17.3, < 2.0) jwt (>= 1.4, < 3.0) memoist (~> 0.16) @@ -158,7 +158,7 @@ GEM ruby2_keywords (0.0.4) rubyzip (2.3.0) security (0.1.3) - signet (0.14.1) + signet (0.15.0) addressable (~> 2.3) faraday (>= 0.17.3, < 2.0) jwt (>= 1.5, < 3.0) diff --git a/android/fastlane/Fastfile b/android/fastlane/Fastfile index 283ff8536..9a7dd2212 100644 --- a/android/fastlane/Fastfile +++ b/android/fastlane/Fastfile @@ -24,6 +24,22 @@ lane :playstore do end platform :android do + +desc "Upload closed alpha app and update store entry" + lane :updateclosed_alpha do + begin + upload_to_play_store( + track: 'alpha', + aab: '../build/app/outputs/bundle/release/app-release.aab', + skip_upload_metadata: false, + skip_upload_images: true, + skip_upload_screenshots: true, + release_status: "completed", #"draft", + ) + end + end + + desc "Runs all the tests" lane :test do gradle(task: "test") diff --git a/android/fastlane/README.md b/android/fastlane/README.md index 9816838ab..af8ee779b 100644 --- a/android/fastlane/README.md +++ b/android/fastlane/README.md @@ -24,6 +24,11 @@ fastlane playstore ---- ## Android +### android updateclosed_beta +``` +fastlane android updateclosed_beta +``` +Update store entry ### android test ``` fastlane android test diff --git a/android/fastlane/metadata/android/nb-NO/title.txt b/android/fastlane/metadata/android/nb-NO/title.txt new file mode 100644 index 000000000..d35e40870 --- /dev/null +++ b/android/fastlane/metadata/android/nb-NO/title.txt @@ -0,0 +1 @@ +wger Workout Manager diff --git a/android/fastlane/report.xml b/android/fastlane/report.xml index d2e72b667..9407b5625 100644 --- a/android/fastlane/report.xml +++ b/android/fastlane/report.xml @@ -5,14 +5,12 @@ - + - - - + diff --git a/pubspec.yaml b/pubspec.yaml index fa8fe101c..658e6a13e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 0.1.0+5 +version: 0.1.0+6 environment: sdk: ">=2.10.0 <3.0.0" From de46307bd4fcc8e5fe0c05d3eb4a72ee58aba6e7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 14 Mar 2021 22:24:30 +0000 Subject: [PATCH 15/58] Translated using Weblate (German) Currently translated at 100.0% (79 of 79 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/de/ --- lib/l10n/app_de.arb | 90 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 1bc4706a8..738f392f7 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -163,5 +163,95 @@ "comment": "Kommentar", "@comment": { "description": "Comment, additional information" + }, + "goToToday": "Zu heute gehen", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "selectIngredient": "Bitte wählen Sie eine Zutat", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" + }, + "enterValidNumber": "Bitte geben Sie eine gültige Zahl ein", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "enterValue": "Bitte geben Sie einen Wert ein", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "calendar": "Kalender", + "@calendar": {}, + "noWeightEntries": "Sie haben keine Gewichtseinträge", + "@noWeightEntries": { + "description": "Message shown when the user has no logged weight entries" + }, + "unit": "Einheit", + "@unit": { + "description": "The unit used for a repetition (kg, time, etc.)" + }, + "logHelpEntriesUnits": "Beachten Sie, dass nur Einträge mit einer Gewichtseinheit (kg oder lb) und Wiederholungen aufgezeichnet werden, andere Kombinationen wie Zeit oder \"bis zum Versagen\" werden hier ignoriert.", + "@logHelpEntriesUnits": {}, + "logHelpEntries": "Gibt es an einem Tag mehrere Einträge mit der gleichen Anzahl von Wiederholungen, aber unterschiedlichen Gewichten, wird nur der Eintrag mit dem höheren Gewicht im Diagramm angezeigt.", + "@logHelpEntries": {}, + "loginInstead": "Stattdessen einloggen", + "@loginInstead": {}, + "registerInstead": "Stattdessen registrieren", + "@registerInstead": {}, + "reset": "Zurücksetzen", + "@reset": { + "description": "Button text allowing the user to reset the entered values to the default" + }, + "customServerHint": "Geben Sie die Adresse Ihres eigenen Servers ein, ansonsten wird die Standardadresse verwendet", + "@customServerHint": { + "description": "Hint text for the form where the users can enter their own wger instance" + }, + "customServerUrl": "URL der wger-Instanz", + "@customServerUrl": { + "description": "Label in the form where the users can enter their own wger instance" + }, + "invalidUsername": "Bitte geben Sie einen gültigen Benutzernamen ein", + "@invalidUsername": { + "description": "Error message when the user enters an invalid username" + }, + "username": "Benutzername", + "@username": {}, + "email": "E-Mail", + "@email": {}, + "invalidEmail": "Bitte geben Sie eine gültigen E-Mail-Adresse ein", + "@invalidEmail": { + "description": "Error message when the user enters an invalid email" + }, + "confirmPassword": "Passwort bestätigen", + "@confirmPassword": {}, + "password": "Passwort", + "@password": {}, + "passwordTooShort": "Das Passwort ist zu kurz", + "@passwordTooShort": { + "description": "Error message when the user a password that is too short" + }, + "passwordsDontMatch": "Die Passwörter stimmen nicht überein", + "@passwordsDontMatch": { + "description": "Error message when the user enters two different passwords during registration" + }, + "invalidUrl": "Bitte geben Sie eine gültige URL ein", + "@invalidUrl": { + "description": "Error message when the user enters an invalid URL, e.g. in the login form" + }, + "useCustomServer": "Benutzerdefinierten Server verwenden", + "@useCustomServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "useDefaultServer": "Standard-Server verwenden", + "@useDefaultServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "register": "Registrieren", + "@register": { + "description": "Text for registration button" + }, + "login": "Anmelden", + "@login": { + "description": "Text for login button" } } From f8a7560da08a26fdce0d317fe9bccd25e9a3e948 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 16 Mar 2021 12:38:32 +0100 Subject: [PATCH 16/58] Show nutritional plan details on dashboard --- lib/widgets/dashboard/widgets.dart | 57 +++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 8f81a12eb..2a035c28b 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -48,11 +48,53 @@ class DashboardNutritionWidget extends StatefulWidget { class _DashboardNutritionWidgetState extends State { Nutrition nutrition; NutritionalPlan plan; + var showDetail = false; @override Widget build(BuildContext context) { plan = Provider.of(context, listen: false).currentPlan; + List out = []; + for (var meal in plan.meals) { + out.add(Text( + meal.time.format(context), + style: TextStyle(fontWeight: FontWeight.bold), + )); + out.add(Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + mainAxisSize: MainAxisSize.min, + children: [ + Text('${meal.nutritionalValues.energy}${AppLocalizations.of(context).kcal}'), + Text(' / '), + Text('${meal.nutritionalValues.protein}${AppLocalizations.of(context).g}'), + Text(' / '), + Text('${meal.nutritionalValues.carbohydrates}${AppLocalizations.of(context).g}'), + Text(' / '), + Text('${meal.nutritionalValues.fat}${AppLocalizations.of(context).g} '), + ], + )); + out.add(SizedBox(height: 5)); + + if (showDetail) { + meal.mealItems.forEach((item) { + out.add( + Column(children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(item.ingredientObj.name), + SizedBox(width: 5), + Text('${item.amount.toString()} ${AppLocalizations.of(context).g}'), + ], + ), + ]), + ); + }); + out.add(SizedBox(height: 10)); + out.add(Divider()); + } + } + return Card( child: Column( mainAxisSize: MainAxisSize.min, @@ -78,6 +120,7 @@ class _DashboardNutritionWidgetState extends State { .pushNamed(NutritionalPlanScreen.routeName, arguments: plan); }, ), + ...out, Container( padding: EdgeInsets.all(15), height: 180, @@ -94,15 +137,13 @@ class _DashboardNutritionWidgetState extends State { mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( - child: const Text('Action one'), - onPressed: () {}, + child: Text(AppLocalizations.of(context).toggleDetails), + onPressed: () { + setState(() { + showDetail = !showDetail; + }); + }, ), - const SizedBox(width: 8), - TextButton( - child: const Text('Action two'), - onPressed: () {}, - ), - const SizedBox(width: 8), ], ), ], From ef645e10f401656ca3d5679c9676c654d351c783 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 16 Mar 2021 22:42:10 +0100 Subject: [PATCH 17/58] Make app more inviting when the user has no workout plans, etc. --- lib/l10n/app_en.arb | 9 + lib/models/nutrition/nutritional_plan.dart | 4 +- lib/models/workouts/workout_plan.dart | 4 +- lib/screens/workout_plan_screen.dart | 14 +- lib/widgets/dashboard/widgets.dart | 214 +++++++++++++-------- lib/widgets/workouts/day.dart | 6 +- 6 files changed, 154 insertions(+), 97 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 2bf8d7417..5923dcb6a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -78,6 +78,11 @@ "@newWorkout": { "description": "Header when adding a new workout" }, + "noWorkoutPlans": "You have no workout plans", + "@noWorkoutPlans": { + "description": "Message shown when the user has no workout plans" + }, + "addExercise": "Add exercise to this day", "repetitions": "Repetitions", "@repetitions": { "description": "Repetitions for an exercise set" @@ -134,6 +139,10 @@ "@nutritionalDiary": {}, "nutritionalPlans": "Nutritional plans", "@nutritionalPlans": {}, + "noNutritionalPlans": "You have no nutritional plans", + "@noNutritionalPlans": { + "description": "Message shown when the user has no nutritional plans" + }, "anErrorOccurred": "An Error Occurred!", "@anErrorOccurred": {}, "dismiss": "Dismiss", diff --git a/lib/models/nutrition/nutritional_plan.dart b/lib/models/nutrition/nutritional_plan.dart index bb662298e..e95f040d1 100644 --- a/lib/models/nutrition/nutritional_plan.dart +++ b/lib/models/nutrition/nutritional_plan.dart @@ -48,7 +48,9 @@ class NutritionalPlan { this.creationDate, this.meals, //this.logs, - }); + }) { + this.meals = meals ?? []; + } // Boilerplate factory NutritionalPlan.fromJson(Map json) => _$NutritionalPlanFromJson(json); diff --git a/lib/models/workouts/workout_plan.dart b/lib/models/workouts/workout_plan.dart index 0dea7e66b..6807a516a 100644 --- a/lib/models/workouts/workout_plan.dart +++ b/lib/models/workouts/workout_plan.dart @@ -45,7 +45,9 @@ class WorkoutPlan { this.creationDate, this.description, this.days, - }); + }) { + this.days = days ?? []; + } // Boilerplate factory WorkoutPlan.fromJson(Map json) => _$WorkoutPlanFromJson(json); diff --git a/lib/screens/workout_plan_screen.dart b/lib/screens/workout_plan_screen.dart index cecf46f78..b03cb2d69 100644 --- a/lib/screens/workout_plan_screen.dart +++ b/lib/screens/workout_plan_screen.dart @@ -81,6 +81,13 @@ class _WorkoutPlanScreenState extends State { SliverAppBar( expandedHeight: 250, pinned: true, + flexibleSpace: FlexibleSpaceBar( + title: Text(workoutPlan.description), + background: Image( + image: AssetImage('assets/images/backgrounds/workout_plans.jpg'), + fit: BoxFit.cover, + ), + ), actions: [ PopupMenuButton( icon: Icon(Icons.more_vert), @@ -129,13 +136,6 @@ class _WorkoutPlanScreenState extends State { }, ), ], - flexibleSpace: FlexibleSpaceBar( - title: Text(workoutPlan.description), - background: Image( - image: AssetImage('assets/images/backgrounds/workout_plans.jpg'), - fit: BoxFit.cover, - ), - ), ), getBody(workoutPlan), ], diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 2a035c28b..eb24c0599 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -28,10 +28,13 @@ import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/workout_plans.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/screens/workout_plan_screen.dart'; +import 'package:wger/theme/theme.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/nutrition/charts.dart'; +import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/weight/charts.dart'; import 'package:wger/widgets/weight/forms.dart'; +import 'package:wger/widgets/workouts/forms.dart'; class DashboardNutritionWidget extends StatefulWidget { const DashboardNutritionWidget({ @@ -53,45 +56,48 @@ class _DashboardNutritionWidgetState extends State { @override Widget build(BuildContext context) { plan = Provider.of(context, listen: false).currentPlan; + final bool hasContent = plan != null; List out = []; - for (var meal in plan.meals) { - out.add(Text( - meal.time.format(context), - style: TextStyle(fontWeight: FontWeight.bold), - )); - out.add(Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - mainAxisSize: MainAxisSize.min, - children: [ - Text('${meal.nutritionalValues.energy}${AppLocalizations.of(context).kcal}'), - Text(' / '), - Text('${meal.nutritionalValues.protein}${AppLocalizations.of(context).g}'), - Text(' / '), - Text('${meal.nutritionalValues.carbohydrates}${AppLocalizations.of(context).g}'), - Text(' / '), - Text('${meal.nutritionalValues.fat}${AppLocalizations.of(context).g} '), - ], - )); - out.add(SizedBox(height: 5)); + if (hasContent) { + for (var meal in plan.meals) { + out.add(Text( + meal.time.format(context), + style: TextStyle(fontWeight: FontWeight.bold), + )); + out.add(Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + mainAxisSize: MainAxisSize.min, + children: [ + Text('${meal.nutritionalValues.energy}${AppLocalizations.of(context).kcal}'), + Text(' / '), + Text('${meal.nutritionalValues.protein}${AppLocalizations.of(context).g}'), + Text(' / '), + Text('${meal.nutritionalValues.carbohydrates}${AppLocalizations.of(context).g}'), + Text(' / '), + Text('${meal.nutritionalValues.fat}${AppLocalizations.of(context).g} '), + ], + )); + out.add(SizedBox(height: 5)); - if (showDetail) { - meal.mealItems.forEach((item) { - out.add( - Column(children: [ - Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(item.ingredientObj.name), - SizedBox(width: 5), - Text('${item.amount.toString()} ${AppLocalizations.of(context).g}'), - ], - ), - ]), - ); - }); - out.add(SizedBox(height: 10)); - out.add(Divider()); + if (showDetail) { + meal.mealItems.forEach((item) { + out.add( + Column(children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(item.ingredientObj.name), + SizedBox(width: 5), + Text('${item.amount.toString()} ${AppLocalizations.of(context).g}'), + ], + ), + ]), + ); + }); + out.add(SizedBox(height: 10)); + out.add(Divider()); + } } } @@ -103,7 +109,7 @@ class _DashboardNutritionWidgetState extends State { AppLocalizations.of(context).nutritionalPlan, style: Theme.of(context).textTheme.headline4, ), - plan != null + hasContent ? Column( children: [ Text( @@ -128,10 +134,10 @@ class _DashboardNutritionWidgetState extends State { ) ], ) - : Container( - alignment: Alignment.center, - height: 150, - child: Text('You have no nutritional plans'), + : NothingFound( + AppLocalizations.of(context).noNutritionalPlans, + AppLocalizations.of(context).newNutritionalPlan, + PlanForm(NutritionalPlan()), ), Row( mainAxisAlignment: MainAxisAlignment.end, @@ -187,10 +193,10 @@ class _DashboardWeightWidgetState extends State { height: 180, child: WeightChartWidget(weightEntriesData.items), ) - : Container( - alignment: Alignment.center, - height: 150, - child: Text(AppLocalizations.of(context).noWeightEntries), + : NothingFound( + AppLocalizations.of(context).noWeightEntries, + AppLocalizations.of(context).newEntry, + WeightForm(), ), Row( mainAxisAlignment: MainAxisAlignment.end, @@ -240,30 +246,33 @@ class _DashboardWorkoutWidgetState extends State { @override Widget build(BuildContext context) { _workoutPlan = Provider.of(context, listen: false).activePlan; + final bool hasContent = _workoutPlan != null; List out = []; - for (var day in _workoutPlan.days) { - out.add(Text( - day.description, - style: TextStyle(fontWeight: FontWeight.bold), - )); - if (showDetail) { - day.sets.forEach((set) { - out.add(Column( - children: [ - ...set.settings.map((s) { - return Column( - children: [ - Text(s.exerciseObj.name), - Text(s.repsText), - SizedBox(height: 10), - ], - ); - }).toList(), - Divider(), - ], - )); - }); + if (hasContent) { + for (var day in _workoutPlan.days) { + out.add(Text( + day.description, + style: TextStyle(fontWeight: FontWeight.bold), + )); + if (showDetail) { + day.sets.forEach((set) { + out.add(Column( + children: [ + ...set.settings.map((s) { + return Column( + children: [ + Text(s.exerciseObj.name), + Text(s.repsText), + SizedBox(height: 10), + ], + ); + }).toList(), + Divider(), + ], + )); + }); + } } } @@ -275,7 +284,7 @@ class _DashboardWorkoutWidgetState extends State { AppLocalizations.of(context).labelWorkoutPlan, style: Theme.of(context).textTheme.headline4, ), - _workoutPlan != null + hasContent ? Column( children: [ Text( @@ -293,26 +302,61 @@ class _DashboardWorkoutWidgetState extends State { }, ), ...out, - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - TextButton( - child: Text(AppLocalizations.of(context).toggleDetails), - onPressed: () { - setState(() { - showDetail = !showDetail; - }); - }, - ), - ], - ) ], ) - : Container( - alignment: Alignment.center, - height: 150, - child: Text('you have no workouts'), + : NothingFound( + AppLocalizations.of(context).noWorkoutPlans, + AppLocalizations.of(context).newWorkout, + WorkoutForm(WorkoutPlan()), ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + child: Text(AppLocalizations.of(context).toggleDetails), + onPressed: () { + setState(() { + showDetail = !showDetail; + }); + }, + ), + ], + ) + ], + ), + ); + } +} + +class NothingFound extends StatelessWidget { + final String _title; + final String _titleForm; + final Widget _form; + + NothingFound(this._title, this._titleForm, this._form); + + @override + Widget build(BuildContext context) { + return Container( + height: 150, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(_title), + IconButton( + iconSize: 30, + icon: const Icon( + Icons.add_box, + color: wgerPrimaryButtonColor, + ), + onPressed: () async { + showFormBottomSheet( + context, + _titleForm, + _form, + ); + }, + ), ], ), ); diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 00b7fd355..fe34ac912 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -100,7 +100,7 @@ class WorkoutDayWidget extends StatelessWidget { ) .toList(), OutlinedButton( - child: Text('Add exercise to day'), + child: Text(AppLocalizations.of(context).addExercise), onPressed: () { showFormBottomSheet( context, @@ -134,7 +134,7 @@ class DayHeaderDismissible extends StatelessWidget { key: Key(_day.id.toString()), direction: DismissDirection.startToEnd, child: Container( - decoration: BoxDecoration(color: Colors.black12), + decoration: BoxDecoration(color: Colors.white), padding: const EdgeInsets.symmetric(vertical: 10), width: double.infinity, child: Column( @@ -193,7 +193,7 @@ class DayHeaderDismissible extends StatelessWidget { content: Text('Would open weight log form for this day'), actions: [ TextButton( - child: Text("Close"), + child: Text(AppLocalizations.of(context).dismiss), onPressed: () => Navigator.of(context).pop(), ), ], From 9397b90870cf52745ed1f1d549d77cd216a34033 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 16 Mar 2021 22:43:05 +0100 Subject: [PATCH 18/58] Parse the login URL so that HTTPS can be used as well --- lib/providers/auth.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index 73389dae7..14428215d 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -79,7 +79,7 @@ class Auth with ChangeNotifier { /// Registers a new user Future register({String username, String password, String email, String serverUrl}) async { - final uri = Uri.http(serverUrl, '/api/v2/register/'); + final uri = Uri.parse(serverUrl + '/api/v2/register/'); Map metadata = Map(); // Read the api key from the manifest file From 0cc240bebcbbb60ef62beac19f2e8019ca2d0157 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 00:13:26 +0100 Subject: [PATCH 19/58] More work with workout and nutritional plans detail page --- lib/theme/theme.dart | 2 + lib/widgets/nutrition/meal.dart | 37 +++++---- lib/widgets/workouts/day.dart | 78 +++++++++++-------- lib/widgets/workouts/workout_plan_detail.dart | 4 +- 4 files changed, 71 insertions(+), 50 deletions(-) diff --git a/lib/theme/theme.dart b/lib/theme/theme.dart index 363a10be2..8a9270c5f 100644 --- a/lib/theme/theme.dart +++ b/lib/theme/theme.dart @@ -24,6 +24,7 @@ const Color wgerPrimaryButtonColor = Color(0xff266dd3); const Color wgerPrimaryColorLight = Color(0xff94B2DB); const Color wgerSecondaryColor = Color(0xffe63946); const Color wgerTextMuted = Colors.black38; +const Color wgerBackground = Color(0xfff4f4f6); // Chart colors const charts.Color wgerChartPrimaryColor = charts.Color(r: 0x2a, g: 0x4c, b: 0x7d); @@ -35,6 +36,7 @@ final ThemeData wgerTheme = ThemeData( */ primaryColor: wgerPrimaryColor, accentColor: wgerSecondaryColor, + scaffoldBackgroundColor: wgerBackground, // This makes the visual density adapt to the platform that you run // the app on. For desktop platforms, the controls will be smaller and diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index c321d4311..4e921ab28 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -169,22 +169,27 @@ class DismissibleMealHeader extends StatelessWidget { child: Dismissible( key: Key(_meal.id.toString()), child: Container( - width: double.infinity, - decoration: BoxDecoration(color: Colors.black12), - padding: const EdgeInsets.all(10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - _meal.time != null ? Text(_meal.time.format(context)) : Text('aaaa'), - IconButton( - visualDensity: VisualDensity.compact, - icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more), - onPressed: () { - _toggle(); - }, - ), - ], - )), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration(color: Colors.white), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _meal.time != null + ? Text( + _meal.time.format(context), + style: Theme.of(context).textTheme.headline5, + ) + : Text(''), + IconButton( + visualDensity: VisualDensity.compact, + icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more), + onPressed: () { + _toggle(); + }, + ), + ], + ), + ), secondaryBackground: Container( color: Theme.of(context).accentColor, padding: EdgeInsets.only(right: 10), diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index fe34ac912..82f411670 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -90,30 +90,30 @@ class WorkoutDayWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return Card( - child: Column( - children: [ - DayHeaderDismissible(day: _day), - ..._day.sets - .map( - (set) => getSetRow(set), - ) - .toList(), - OutlinedButton( - child: Text(AppLocalizations.of(context).addExercise), - onPressed: () { - showFormBottomSheet( - context, - AppLocalizations.of(context).newSet, - SetFormWidget(_day), - scrollControlled: true, - ); - }, - ), - Padding( - padding: const EdgeInsets.symmetric(vertical: 10.0), - ) - ], + return Container( + padding: EdgeInsets.all(3), + child: Card( + child: Column( + children: [ + DayHeaderDismissible(day: _day), + ..._day.sets + .map( + (set) => getSetRow(set), + ) + .toList(), + OutlinedButton( + child: Text(AppLocalizations.of(context).addExercise), + onPressed: () { + showFormBottomSheet( + context, + AppLocalizations.of(context).newSet, + SetFormWidget(_day), + scrollControlled: true, + ); + }, + ), + ], + ), ), ); } @@ -134,22 +134,34 @@ class DayHeaderDismissible extends StatelessWidget { key: Key(_day.id.toString()), direction: DismissDirection.startToEnd, child: Container( + padding: const EdgeInsets.all(10), decoration: BoxDecoration(color: Colors.white), - padding: const EdgeInsets.symmetric(vertical: 10), - width: double.infinity, - child: Column( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text( - _day.description, - style: Theme.of(context).textTheme.headline6, + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _day.description, + style: Theme.of(context).textTheme.headline5, + ), + Text(_day.getDaysText), + ], ), - Text(_day.getDaysText), + /* + IconButton( + visualDensity: VisualDensity.compact, + icon: Icon(Icons.expand_less), + onPressed: () {}, + ), + */ ], ), ), /* secondaryBackground: Container( - color: Theme.of(context).primaryColor, + color: Theme.of(context).accentColor, padding: EdgeInsets.only(right: 10), child: Row( mainAxisAlignment: MainAxisAlignment.end, @@ -167,7 +179,7 @@ class DayHeaderDismissible extends StatelessWidget { ), */ background: Container( - color: Theme.of(context).accentColor, + color: Theme.of(context).primaryColor, alignment: Alignment.centerLeft, padding: EdgeInsets.only(left: 10), child: Row( diff --git a/lib/widgets/workouts/workout_plan_detail.dart b/lib/widgets/workouts/workout_plan_detail.dart index 83bee4b8a..5e864cf7a 100644 --- a/lib/widgets/workouts/workout_plan_detail.dart +++ b/lib/widgets/workouts/workout_plan_detail.dart @@ -18,7 +18,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; -import 'package:intl/intl.dart'; import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/screens/workout_plan_screen.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; @@ -42,6 +41,7 @@ class _WorkoutPlanDetailState extends State { [ Column( children: [ + /* Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: Text( @@ -49,6 +49,8 @@ class _WorkoutPlanDetailState extends State { style: Theme.of(context).textTheme.headline6, ), ), + + */ ...widget._workoutPlan.days .map((workoutDay) => WorkoutDayWidget(workoutDay)) .toList(), From dfad43b43e169730703d1ffdb04aa35632787066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Tue, 16 Mar 2021 21:03:46 +0000 Subject: [PATCH 20/58] Translated using Weblate (English) Currently translated at 100.0% (79 of 79 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/en/ --- lib/l10n/app_en.arb | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 5923dcb6a..a3908f755 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1,6 +1,6 @@ { "@@last_modified": "2020-11-11T15:04:05.523531", - "login": "Login", + "login": "Log in", "@login": { "description": "Text for login button" }, @@ -29,13 +29,17 @@ "description": "Error message when the user a password that is too short" }, "password": "Password", + "@password": {}, "confirmPassword": "Confirm password", - "invalidEmail": "Please enter a valid email address", + "@confirmPassword": {}, + "invalidEmail": "Please enter a valid e-mail address", "@invalidEmail": { "description": "Error message when the user enters an invalid email" }, - "email": "Email", + "email": "E-mail address", + "@email": {}, "username": "Username", + "@username": {}, "invalidUsername": "Please enter a valid username", "@invalidUsername": { "description": "Error message when the user enters an invalid username" @@ -53,7 +57,9 @@ "description": "Button text allowing the user to reset the entered values to the default" }, "registerInstead": "Register instead", - "loginInstead": "Login instead", + "@registerInstead": {}, + "loginInstead": "Log in instead", + "@loginInstead": {}, "labelWorkoutPlans": "Workout plans", "@labelWorkoutPlans": { "description": "Title for screen workout plans" @@ -118,7 +124,9 @@ "description": "Label when starting the gym mode" }, "logHelpEntries": "If on a single day there is more than one entry with the same number of repetitions, but different weights, only the entry with the higher weight is shown in the diagram.", + "@logHelpEntries": {}, "logHelpEntriesUnits": "Note that only entries with a weight unit (kg or lb) and repetitions are charted, other combinations such as time or until failure are ignored here.", + "@logHelpEntriesUnits": {}, "description": "Description", "@description": {}, "save": "Save", @@ -234,6 +242,7 @@ "description": "Text in the about dialog" }, "calendar": "Calendar", + "@calendar": {}, "goToToday": "Go to today", "@goToToday": { "description": "Label on button to jump back to 'today' in the calendar widget" From c248cf3a3135f250177ba3f04283c3705c1beddc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allan=20Nordh=C3=B8y?= Date: Tue, 16 Mar 2021 21:12:04 +0000 Subject: [PATCH 21/58] =?UTF-8?q?Translated=20using=20Weblate=20(Norwegian?= =?UTF-8?q?=20Bokm=C3=A5l)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently translated at 100.0% (79 of 79 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/nb_NO/ --- lib/l10n/app_nb.arb | 90 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/lib/l10n/app_nb.arb b/lib/l10n/app_nb.arb index e0375f6a6..8e283dc7f 100644 --- a/lib/l10n/app_nb.arb +++ b/lib/l10n/app_nb.arb @@ -158,5 +158,95 @@ "labelWorkoutPlans": "Treningsøktplaner", "@labelWorkoutPlans": { "description": "Title for screen workout plans" + }, + "logHelpEntriesUnits": "Kun oppføringer med vekt vises, ingen andre kombinasjoner.", + "@logHelpEntriesUnits": {}, + "logHelpEntries": "Kun tyngre vekt vises hvis én dag har forskjellige vekter med samme antall repetisjoner.", + "@logHelpEntries": {}, + "login": "Logg inn", + "@login": { + "description": "Text for login button" + }, + "loginInstead": "Logg inn istedenfor", + "@loginInstead": {}, + "email": "E-postadresse", + "@email": {}, + "invalidEmail": "Skriv inn en gyldig e-postadresse", + "@invalidEmail": { + "description": "Error message when the user enters an invalid email" + }, + "register": "Registrer", + "@register": { + "description": "Text for registration button" + }, + "selectIngredient": "Velg en ingrediens", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" + }, + "enterValidNumber": "Skriv inn et gyldig nummer", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "enterValue": "Skriv inn en verdi", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "goToToday": "Gå til dagens dato", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "calendar": "Kalender", + "@calendar": {}, + "noWeightEntries": "Du har ingen vektoppføringer", + "@noWeightEntries": { + "description": "Message shown when the user has no logged weight entries" + }, + "unit": "Enhet", + "@unit": { + "description": "The unit used for a repetition (kg, time, etc.)" + }, + "registerInstead": "Registrer istedenfor", + "@registerInstead": {}, + "reset": "Tilbakestill", + "@reset": { + "description": "Button text allowing the user to reset the entered values to the default" + }, + "customServerHint": "Skriv inn adressen til din egen tjener, ellers vil den forvalgte brukes", + "@customServerHint": { + "description": "Hint text for the form where the users can enter their own wger instance" + }, + "customServerUrl": "Nettadresse til wger-instansen", + "@customServerUrl": { + "description": "Label in the form where the users can enter their own wger instance" + }, + "invalidUsername": "Skriv inn et gyldig brukernavn", + "@invalidUsername": { + "description": "Error message when the user enters an invalid username" + }, + "username": "Brukernavn", + "@username": {}, + "confirmPassword": "Bekreft passord", + "@confirmPassword": {}, + "password": "Passord", + "@password": {}, + "passwordTooShort": "Passordet er for kort", + "@passwordTooShort": { + "description": "Error message when the user a password that is too short" + }, + "passwordsDontMatch": "Passordene samsvarer ikke", + "@passwordsDontMatch": { + "description": "Error message when the user enters two different passwords during registration" + }, + "invalidUrl": "Skriv inn en gyldig nettadresse", + "@invalidUrl": { + "description": "Error message when the user enters an invalid URL, e.g. in the login form" + }, + "useCustomServer": "Bruk egendefinert tjener", + "@useCustomServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "useDefaultServer": "Bruk forvalgt tjener", + "@useDefaultServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" } } From 438ce00e0a4a27e6133ec48aaf6e6cb6d2b1f62a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 12:00:18 +0100 Subject: [PATCH 22/58] Use workout description as title and date as subtitle This makes more sense and is consistent with the nutritional plan list --- lib/widgets/workouts/workout_plans_list.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/widgets/workouts/workout_plans_list.dart b/lib/widgets/workouts/workout_plans_list.dart index f7aab079f..8dda98e92 100644 --- a/lib/widgets/workouts/workout_plans_list.dart +++ b/lib/widgets/workouts/workout_plans_list.dart @@ -99,8 +99,8 @@ class WorkoutPlansList extends StatelessWidget { return Navigator.of(context) .pushNamed(WorkoutPlanScreen.routeName, arguments: currentWorkout); }, - title: Text(DateFormat.yMd().format(currentWorkout.creationDate)), - subtitle: Text(currentWorkout.description), + title: Text(currentWorkout.description), + subtitle: Text(DateFormat.yMd().format(currentWorkout.creationDate)), ), ), ); From 5aa55b2f4d3fe2e65b512018fec2512dc4339984 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 12:49:43 +0100 Subject: [PATCH 23/58] Round nutritional values in the dashboard --- lib/widgets/dashboard/widgets.dart | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index eb24c0599..20031f64b 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -69,13 +69,17 @@ class _DashboardNutritionWidgetState extends State { mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisSize: MainAxisSize.min, children: [ - Text('${meal.nutritionalValues.energy}${AppLocalizations.of(context).kcal}'), + Text( + '${meal.nutritionalValues.energy.toStringAsFixed(0)}${AppLocalizations.of(context).kcal}'), Text(' / '), - Text('${meal.nutritionalValues.protein}${AppLocalizations.of(context).g}'), + Text( + '${meal.nutritionalValues.protein.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), Text(' / '), - Text('${meal.nutritionalValues.carbohydrates}${AppLocalizations.of(context).g}'), + Text( + '${meal.nutritionalValues.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), Text(' / '), - Text('${meal.nutritionalValues.fat}${AppLocalizations.of(context).g} '), + Text( + '${meal.nutritionalValues.fat.toStringAsFixed(0)}${AppLocalizations.of(context).g} '), ], )); out.add(SizedBox(height: 5)); From 9f1332549d507f9d6691ed4122afeeb0af92afe0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 12:50:59 +0100 Subject: [PATCH 24/58] I18n more confirmation messages --- lib/helpers/ui.dart | 4 ++-- lib/l10n/app_en.arb | 8 ++++++++ lib/widgets/workouts/workout_plans_list.dart | 11 +++++++---- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/lib/helpers/ui.dart b/lib/helpers/ui.dart index a8b006ddc..e7389ab41 100644 --- a/lib/helpers/ui.dart +++ b/lib/helpers/ui.dart @@ -30,11 +30,11 @@ void showErrorDialog(dynamic exception, BuildContext context) { showDialog( context: context, builder: (ctx) => AlertDialog( - title: Text('An Error Occurred!'), + title: Text(AppLocalizations.of(context).anErrorOccurred), content: Text(exception.toString()), actions: [ TextButton( - child: Text('Dismiss'), + child: Text(AppLocalizations.of(context).dismiss), onPressed: () { Navigator.of(ctx).pop(); }, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 5923dcb6a..fec65f4cd 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -223,6 +223,14 @@ }, "delete": "Delete", "@delete": {}, + "confirmDelete": "Are you sure you want to delete '{toDelete}'?", + "@confirmDelete": { + "description": "Confirmation text before the user deletes an object", + "type": "text", + "placeholders": { + "toDelete": {} + } + }, "newNutritionalPlan": "New nutritional plan", "@newNutritionalPlan": {}, "toggleDetails": "Toggle details", diff --git a/lib/widgets/workouts/workout_plans_list.dart b/lib/widgets/workouts/workout_plans_list.dart index 8dda98e92..aa06aaf4f 100644 --- a/lib/widgets/workouts/workout_plans_list.dart +++ b/lib/widgets/workouts/workout_plans_list.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:wger/providers/workout_plans.dart'; @@ -42,15 +43,17 @@ class WorkoutPlansList extends StatelessWidget { context: context, builder: (BuildContext contextDialog) { return AlertDialog( - content: Text("Are you sure you want to delete ${currentWorkout.description}?"), + content: Text( + AppLocalizations.of(context).confirmDelete(currentWorkout.description), + ), actions: [ TextButton( - child: Text("Cancel"), + child: Text(AppLocalizations.of(context).cancel), onPressed: () => Navigator.of(contextDialog).pop(), ), TextButton( child: Text( - "Delete", + AppLocalizations.of(context).delete, style: TextStyle(color: Theme.of(context).errorColor), ), onPressed: () { @@ -65,7 +68,7 @@ class WorkoutPlansList extends StatelessWidget { Scaffold.of(context).showSnackBar( SnackBar( content: Text( - 'Workout "${currentWorkout.description}" deleted', + AppLocalizations.of(context).successfullyDeleted, textAlign: TextAlign.center, ), ), From 495dcf21bc45f8edfe9c43a43a81cb74cfe99c45 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 20:56:38 +0100 Subject: [PATCH 25/58] Update README with instructions for the wger.properties config file --- README.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ff1fff688..81cd3eeec 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,26 @@ Install flutter, all its dependencies and create a new virtual device: ### 3 -Generate translation files with ``flutter gen-l10n`` +Create a new file ``wger.properties`` in ``android/app`` (next to build.gradle): + +```properties +WGER_API_KEY=123456 +``` + +To just run/develop the app it only needs to have any value for WGER_API_KEY, but +you need a correct value if you want to register via the app. For this you need +to allow (a probably dedicated) user on the wger server to register users in its +behalf. For this, generate an API KEY by visiting +on your local instance and then run ``python3 manage.py add-user-rest theusername`` + +You can later list all the registered users with: ``python3 manage.py list-users-api`` ### 4 +Generate translation files with ``flutter gen-l10n`` + + +### 5 Start the application with ``flutter run`` or use your IDE (please note that depending on how you run your emulator you will need to change the IP address of the server) From 673f89900e85e625ee132e81d3b1b525d85e5f79 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 23:41:53 +0100 Subject: [PATCH 26/58] Add link to weblate in README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 81cd3eeec..8b7e38239 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Mobile app for wger +# Mobile app for wger Workout Manager Mobile app for wger written with flutter, still in early stages of development. As soon as it is finished, it will be published in the different play stores. @@ -40,6 +40,9 @@ Start the application with ``flutter run`` or use your IDE (please note that depending on how you run your emulator you will need to change the IP address of the server) +## Translation +The application can be easily translated online with [Weblate](https://hosted.weblate.org/engage/wger/). + ## Contact From 97d025c52946fd3024d91d8b20766cc7652f9297 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 17 Mar 2021 23:42:32 +0100 Subject: [PATCH 27/58] Make behaviour of workout and nutritional plans more consistent --- lib/widgets/nutrition/meal.dart | 91 ++++++++------ .../nutrition/nutritional_plan_detail.dart | 3 +- .../nutrition/nutritional_plans_list.dart | 51 ++++++-- lib/widgets/workouts/day.dart | 116 ++++++++++++++---- 4 files changed, 183 insertions(+), 78 deletions(-) diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index 4e921ab28..98aa021f7 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -22,6 +22,7 @@ import 'package:provider/provider.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/providers/nutrition.dart'; +import 'package:wger/theme/theme.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -98,45 +99,55 @@ class MealItemWidget extends StatelessWidget { : _item.weightUnit.weightUnit.name; final values = _item.nutritionalValues; - return InkWell( - onLongPress: () { - // Delete the meal item - Provider.of(context, listen: false).deleteMealItem(_item); + return Container( + padding: EdgeInsets.all(5), + child: Column( + children: [ + Container( + width: double.infinity, + padding: EdgeInsets.symmetric(vertical: 5), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: Text( + '${_item.amount.toStringAsFixed(0)}$unit ${_item.ingredientObj.name}', + overflow: TextOverflow.ellipsis, + )), + if (_expanded) + IconButton( + icon: Icon(Icons.delete), + iconSize: 20, + onPressed: () { + // Delete the meal item + Provider.of(context, listen: false).deleteMealItem(_item); - // and inform the user - Scaffold.of(context).showSnackBar(SnackBar( - content: Text( - AppLocalizations.of(context).successfullyDeleted, - textAlign: TextAlign.center, - ))); - }, - child: Container( - padding: EdgeInsets.all(5), - child: Column( - children: [ - Container( - width: double.infinity, - padding: EdgeInsets.symmetric(vertical: 5), - child: Text( - '${_item.amount.toStringAsFixed(0)}$unit ${_item.ingredientObj.name}', - textAlign: TextAlign.left, - ), + // and inform the user + Scaffold.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context).successfullyDeleted, + textAlign: TextAlign.center, + )), + ); + }, + ), + ], ), - if (_expanded) - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - MutedText( - '${values.energy.toStringAsFixed(0)} ${AppLocalizations.of(context).kcal}'), - MutedText( - '${values.protein.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), - MutedText( - '${values.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), - MutedText('${values.fat.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), - ], - ), - ], - ), + ), + if (_expanded) + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + MutedText( + '${values.energy.toStringAsFixed(0)} ${AppLocalizations.of(context).kcal}'), + MutedText('${values.protein.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + MutedText( + '${values.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + MutedText('${values.fat.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + ], + ), + ], ), ); } @@ -204,11 +215,11 @@ class DismissibleMealHeader extends StatelessWidget { ), ), background: Container( - color: Theme.of(context).primaryColor, + color: wgerPrimaryButtonColor, //Theme.of(context).primaryColor, alignment: Alignment.centerLeft, padding: EdgeInsets.only(left: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Log this meal', diff --git a/lib/widgets/nutrition/nutritional_plan_detail.dart b/lib/widgets/nutrition/nutritional_plan_detail.dart index 41bfb0461..a95e4a723 100644 --- a/lib/widgets/nutrition/nutritional_plan_detail.dart +++ b/lib/widgets/nutrition/nutritional_plan_detail.dart @@ -38,8 +38,7 @@ class NutritionalPlanDetailWidget extends StatelessWidget { delegate: SliverChildListDelegate( [ SizedBox(height: 10), - if (_nutritionalPlan.meals != null && _nutritionalPlan.meals.length > 0) - ..._nutritionalPlan.meals.map((meal) => MealWidget(meal)).toList(), + ..._nutritionalPlan.meals.map((meal) => MealWidget(meal)).toList(), Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index 679b2dbd9..d79bee2b8 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -17,6 +17,7 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; @@ -34,19 +35,47 @@ class NutritionalPlansList extends StatelessWidget { final currentPlan = _nutritrionProvider.items[index]; return Dismissible( key: Key(currentPlan.id.toString()), - onDismissed: (direction) { + confirmDismiss: (direction) async { // Delete workout from DB - _nutritrionProvider.deletePlan(currentPlan.id); + final bool res = await showDialog( + context: context, + builder: (BuildContext contextDialog) { + return AlertDialog( + content: Text( + AppLocalizations.of(context).confirmDelete(currentPlan.description), + ), + actions: [ + TextButton( + child: Text(AppLocalizations.of(context).cancel), + onPressed: () => Navigator.of(contextDialog).pop(), + ), + TextButton( + child: Text( + AppLocalizations.of(context).delete, + style: TextStyle(color: Theme.of(context).errorColor), + ), + onPressed: () { + // Confirmed, delete the workout + _nutritrionProvider.deletePlan(currentPlan.id); - // and inform the user - Scaffold.of(context).showSnackBar( - SnackBar( - content: Text( - "Nutritional plan ${currentPlan.id} deleted", - textAlign: TextAlign.center, - ), - ), - ); + // Close the popup + Navigator.of(contextDialog).pop(); + + // and inform the user + Scaffold.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context).successfullyDeleted, + textAlign: TextAlign.center, + ), + ), + ); + }, + ), + ], + ); + }); + return res; }, background: Container( color: Theme.of(context).errorColor, diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 82f411670..a7335e633 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -24,13 +24,16 @@ import 'package:wger/models/workouts/set.dart'; import 'package:wger/models/workouts/setting.dart'; import 'package:wger/providers/workout_plans.dart'; import 'package:wger/screens/gym_mode.dart'; +import 'package:wger/theme/theme.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/workouts/forms.dart'; class SettingWidget extends StatelessWidget { Setting setting; + final bool expanded; + final toggle; - SettingWidget({this.setting}); + SettingWidget({this.setting, this.expanded, this.toggle}); @override Widget build(BuildContext context) { @@ -50,23 +53,36 @@ class SettingWidget extends StatelessWidget { ), title: Text(setting.exerciseObj.name), subtitle: Text(setting.repsText), - trailing: IconButton( - visualDensity: VisualDensity.compact, - icon: Icon(Icons.delete), - //iconSize: 16, - onPressed: () { - Provider.of(context, listen: false).deleteSetting(setting); - }, - ), + trailing: expanded + ? IconButton( + visualDensity: VisualDensity.compact, + icon: Icon(Icons.delete), + onPressed: () { + Provider.of(context, listen: false).deleteSetting(setting); + }, + ) + : SizedBox(width: 1), ); } } -class WorkoutDayWidget extends StatelessWidget { +class WorkoutDayWidget extends StatefulWidget { final Day _day; WorkoutDayWidget(this._day); + @override + _WorkoutDayWidgetState createState() => _WorkoutDayWidgetState(); +} + +class _WorkoutDayWidgetState extends State { + bool _expanded = false; + void _toggleExpanded() { + setState(() { + _expanded = !_expanded; + }); + } + Widget getSetRow(Set set) { return Row( crossAxisAlignment: CrossAxisAlignment.baseline, @@ -77,7 +93,11 @@ class WorkoutDayWidget extends StatelessWidget { children: [ ...set.settings .map( - (setting) => SettingWidget(setting: setting), + (setting) => SettingWidget( + setting: setting, + expanded: _expanded, + toggle: _toggleExpanded, + ), ) .toList(), Divider(), @@ -95,8 +115,36 @@ class WorkoutDayWidget extends StatelessWidget { child: Card( child: Column( children: [ - DayHeaderDismissible(day: _day), - ..._day.sets + DayHeaderDismissible( + day: widget._day, + expanded: _expanded, + toggle: _toggleExpanded, + ), + if (_expanded) + InkWell( + onTap: () { + Navigator.of(context).pushNamed(GymModeScreen.routeName, arguments: widget._day); + }, + child: Container( + width: double.infinity, + height: 50, + color: wgerPrimaryButtonColor, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + AppLocalizations.of(context).gymMode, + style: TextStyle(color: Colors.white), + ), + Icon( + Icons.play_arrow, + color: Colors.white, + ), + ], + ), + ), + ), + ...widget._day.sets .map( (set) => getSetRow(set), ) @@ -107,7 +155,7 @@ class WorkoutDayWidget extends StatelessWidget { showFormBottomSheet( context, AppLocalizations.of(context).newSet, - SetFormWidget(_day), + SetFormWidget(widget._day), scrollControlled: true, ); }, @@ -120,14 +168,20 @@ class WorkoutDayWidget extends StatelessWidget { } class DayHeaderDismissible extends StatelessWidget { + final Day _day; + final bool _expanded; + final _toggle; + const DayHeaderDismissible({ Key key, @required Day day, + @required bool expanded, + @required Function toggle, }) : _day = day, + _expanded = expanded, + _toggle = toggle, super(key: key); - final Day _day; - @override Widget build(BuildContext context) { return Dismissible( @@ -137,7 +191,7 @@ class DayHeaderDismissible extends StatelessWidget { padding: const EdgeInsets.all(10), decoration: BoxDecoration(color: Colors.white), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + //mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -149,13 +203,25 @@ class DayHeaderDismissible extends StatelessWidget { Text(_day.getDaysText), ], ), + Expanded(child: Container()), /* - IconButton( - visualDensity: VisualDensity.compact, - icon: Icon(Icons.expand_less), - onPressed: () {}, - ), + if (_expanded) + IconButton( + icon: Icon(Icons.edit), + onPressed: () {}, + ), + if (_expanded) + IconButton( + icon: Icon(Icons.delete), + onPressed: () {}, + ), */ + IconButton( + icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more), + onPressed: () { + _toggle(); + }, + ), ], ), ), @@ -179,11 +245,11 @@ class DayHeaderDismissible extends StatelessWidget { ), */ background: Container( - color: Theme.of(context).primaryColor, + color: wgerPrimaryButtonColor, //Theme.of(context).primaryColor, alignment: Alignment.centerLeft, padding: EdgeInsets.only(left: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, children: [ Text( AppLocalizations.of(context).gymMode, From 07e51ac3a6ef71adf6e68bde4538d3c9988c0c45 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Mar 2021 10:45:15 +0100 Subject: [PATCH 28/58] Allow deleting whole sets, not settings --- lib/providers/workout_plans.dart | 22 +++++++++++----------- lib/widgets/workouts/day.dart | 19 +++++++++---------- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index b42231cc3..b3cf35e9a 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -359,6 +359,17 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { return set; } + Future deleteSet(Set workoutSet) async { + await deleteRequest(_setsUrlPath, workoutSet.id); + + for (var workout in _workoutPlans) { + for (var day in workout.days) { + day.sets.removeWhere((element) => element.id == workoutSet.id); + } + } + notifyListeners(); + } + /* * Setting */ @@ -369,17 +380,6 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { return setting; } - Future deleteSetting(Setting workoutSetting) async { - await deleteRequest(_settingsUrlPath, workoutSetting.id); - - for (var workout in _workoutPlans) { - for (var day in workout.days) { - day.sets.removeWhere((element) => element.id == workoutSetting.setId); - } - } - notifyListeners(); - } - /* * Sessions */ diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index a7335e633..66c320dc7 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -53,15 +53,6 @@ class SettingWidget extends StatelessWidget { ), title: Text(setting.exerciseObj.name), subtitle: Text(setting.repsText), - trailing: expanded - ? IconButton( - visualDensity: VisualDensity.compact, - icon: Icon(Icons.delete), - onPressed: () { - Provider.of(context, listen: false).deleteSetting(setting); - }, - ) - : SizedBox(width: 1), ); } } @@ -103,7 +94,15 @@ class _WorkoutDayWidgetState extends State { Divider(), ], ), - ) + ), + if (_expanded) + IconButton( + visualDensity: VisualDensity.compact, + icon: Icon(Icons.delete), + onPressed: () { + Provider.of(context, listen: false).deleteSet(set); + }, + ) ], ); } From 06e30c8b0a0c187896bc4b7f1aa047a7fc0e5e13 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Mar 2021 10:51:43 +0100 Subject: [PATCH 29/58] Simplify start page for gym mode --- lib/l10n/app_en.arb | 1 + lib/widgets/workouts/gym_mode.dart | 10 +--------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 6b17626e0..8fa3e88b9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -123,6 +123,7 @@ "@gymMode": { "description": "Label when starting the gym mode" }, + "todaysWorkout": "Your workout today", "logHelpEntries": "If on a single day there is more than one entry with the same number of repetitions, but different weights, only the entry with the higher weight is shown in the diagram.", "@logHelpEntries": {}, "logHelpEntriesUnits": "Note that only entries with a weight unit (kg or lb) and repetitions are charted, other combinations such as time or until failure are ignored here.", diff --git a/lib/widgets/workouts/gym_mode.dart b/lib/widgets/workouts/gym_mode.dart index 11cd5fc39..8a9b37def 100644 --- a/lib/widgets/workouts/gym_mode.dart +++ b/lib/widgets/workouts/gym_mode.dart @@ -104,18 +104,10 @@ class StartPage extends StatelessWidget { Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: Text( - AppLocalizations.of(context).gymMode, + AppLocalizations.of(context).todaysWorkout, style: Theme.of(context).textTheme.headline5, ), ), - Padding( - padding: const EdgeInsets.symmetric(vertical: 10), - child: Text( - _day.description, - style: Theme.of(context).textTheme.headline6, - ), - ), - Text('Your workout today'), ..._day.sets.map( (set) { return Column( From 892e9657c2cdaa067164c1baf740d8b5c75c98ea Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Mar 2021 11:03:44 +0100 Subject: [PATCH 30/58] Alow the user to delete workout days --- lib/helpers/consts.dart | 19 +++++++++++++++++++ lib/providers/workout_plans.dart | 8 ++++++++ lib/widgets/nutrition/meal.dart | 3 ++- lib/widgets/workouts/day.dart | 8 ++++++-- 4 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 lib/helpers/consts.dart diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart new file mode 100644 index 000000000..595a46151 --- /dev/null +++ b/lib/helpers/consts.dart @@ -0,0 +1,19 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (C) 2020 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * wger Workout Manager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +const double ICON_SIZE_SMALL = 20; diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index b3cf35e9a..764292911 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -349,6 +349,14 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { return day; } + Future deleteDay(Day day) async { + await deleteRequest(_daysUrlPath, day.id); + for (var workout in _workoutPlans) { + workout.days.removeWhere((element) => element.id == day.id); + } + notifyListeners(); + } + /* * Sets */ diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index 98aa021f7..8b04f59b7 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/providers/nutrition.dart'; @@ -117,7 +118,7 @@ class MealItemWidget extends StatelessWidget { if (_expanded) IconButton( icon: Icon(Icons.delete), - iconSize: 20, + iconSize: ICON_SIZE_SMALL, onPressed: () { // Delete the meal item Provider.of(context, listen: false).deleteMealItem(_item); diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 66c320dc7..c89ecf165 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/models/workouts/day.dart'; import 'package:wger/models/workouts/set.dart'; import 'package:wger/models/workouts/setting.dart'; @@ -99,6 +100,7 @@ class _WorkoutDayWidgetState extends State { IconButton( visualDensity: VisualDensity.compact, icon: Icon(Icons.delete), + iconSize: ICON_SIZE_SMALL, onPressed: () { Provider.of(context, listen: false).deleteSet(set); }, @@ -209,12 +211,14 @@ class DayHeaderDismissible extends StatelessWidget { icon: Icon(Icons.edit), onPressed: () {}, ), + */ if (_expanded) IconButton( icon: Icon(Icons.delete), - onPressed: () {}, + onPressed: () { + Provider.of(context, listen: false).deleteDay(_day); + }, ), - */ IconButton( icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more), onPressed: () { From 81b94d976cd3c70e10eaf3090e689da7b9e80f74 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Mar 2021 11:14:50 +0100 Subject: [PATCH 31/58] Bump pinned versions --- pubspec.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pubspec.yaml b/pubspec.yaml index 658e6a13e..c16ac2e01 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 0.1.0+6 +version: 0.1.0+7 environment: sdk: ">=2.10.0 <3.0.0" @@ -29,7 +29,7 @@ dependencies: provider: ^5.0.0 intl: ^0.17.0 http: ^0.13.0 - shared_preferences: ^2.0.3 + shared_preferences: ^2.0.5 flutter_calendar_carousel: ^1.5.3 cupertino_icons: ^1.0.0 json_annotation: ^4.0.0 @@ -44,8 +44,8 @@ dev_dependencies: flutter_test: sdk: flutter flutter_launcher_icons: ^0.9.0 - mockito: ^5.0.0 - json_serializable: ^4.0.2 + mockito: ^5.0.2 + json_serializable: ^4.0.3 # Note that there are incompatibilities when using a higher version. Both build # runner and intl_translation depend on different versions of analyzer From 1ad4e5aebb73713ec0b77e2155197739721730cf Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Mar 2021 11:15:13 +0100 Subject: [PATCH 32/58] Move default server to constants file --- lib/helpers/consts.dart | 6 ++++++ lib/providers/auth.dart | 4 ++-- lib/screens/auth_screen.dart | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index 595a46151..d6e113ec1 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -16,4 +16,10 @@ * along with this program. If not, see . */ +/// Size for the "smaller" icons, e.g. when they belong to less important items +/// and we don't want to fill the whole screen const double ICON_SIZE_SMALL = 20; + +/// Default wger server during login +final DEFAULT_SERVER = 'https://wger.rge.uber.space'; +//final DEFAULT_SERVER = 'http://localhost:8000'; diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index 14428215d..aca622a55 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -28,12 +28,11 @@ import 'package:flutter/widgets.dart'; import 'package:http/http.dart' as http; import 'package:package_info/package_info.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/models/http_exception.dart'; import 'helpers.dart'; -final DEFAULT_SERVER = 'https://wger.rge.uber.space'; - class Auth with ChangeNotifier { String token; String serverUrl; @@ -209,6 +208,7 @@ class Auth with ChangeNotifier { log('logging out'); token = null; serverUrl = null; + dataInit = false; // _userId = null; // _expiryDate = null; // if (_authTimer != null) { diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index 44d9d5747..a531746f1 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -19,6 +19,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/ui.dart'; import 'package:wger/models/http_exception.dart'; From 7797eb3d0e205f13c3e1dcf4b8d74391dc10def8 Mon Sep 17 00:00:00 2001 From: Stefano Rossi Date: Thu, 18 Mar 2021 14:17:56 +0100 Subject: [PATCH 33/58] Added translation using Weblate (Italian) --- lib/l10n/app_it.arb | 1 + 1 file changed, 1 insertion(+) create mode 100644 lib/l10n/app_it.arb diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/lib/l10n/app_it.arb @@ -0,0 +1 @@ +{} From 852d072672629ac3a07f13e1f33df43c36faa617 Mon Sep 17 00:00:00 2001 From: Stefano Rossi Date: Thu, 18 Mar 2021 17:08:08 +0100 Subject: [PATCH 34/58] Added translation using Weblate (French) --- lib/l10n/app_fr.arb | 1 + 1 file changed, 1 insertion(+) create mode 100644 lib/l10n/app_fr.arb diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/lib/l10n/app_fr.arb @@ -0,0 +1 @@ +{} From d4ca43291d1f01fe7c532eab4f9fa1adeb9fdef8 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 18 Mar 2021 22:10:43 +0100 Subject: [PATCH 35/58] Skip auth card tests and add body weight ones --- lib/screens/auth_screen.dart | 2 +- lib/screens/weight_screen.dart | 11 +---- lib/widgets/weight/entries_list.dart | 7 ++- pubspec.lock | 42 +++++++++--------- test/auth_screen_test.dart | 48 ++++++++++++++++++-- test/weight_model_test.dart | 12 +++++ test/weight_screen_test.dart | 66 ++++++++++++++++++++++++++++ 7 files changed, 149 insertions(+), 39 deletions(-) create mode 100644 test/weight_screen_test.dart diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index a531746f1..9f2bebae3 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -113,7 +113,7 @@ class _AuthCardState extends State { void initState() { //_serverUrlController.text super.initState(); - Provider.of(context, listen: false).getServerUrlFromPrefs().then((value) { + context.read().getServerUrlFromPrefs().then((value) { _serverUrlController.text = value; }); } diff --git a/lib/screens/weight_screen.dart b/lib/screens/weight_screen.dart index c4d985c72..3a7a69334 100644 --- a/lib/screens/weight_screen.dart +++ b/lib/screens/weight_screen.dart @@ -18,9 +18,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; -import 'package:provider/provider.dart'; -import 'package:wger/models/body_weight/weight_entry.dart'; -import 'package:wger/providers/body_weight.dart'; import 'package:wger/widgets/app_drawer.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/weight/entries_list.dart'; @@ -34,8 +31,6 @@ class WeightScreen extends StatefulWidget { } class _WeightScreenState extends State { - WeightEntry weightEntry = WeightEntry(); - Widget getAppBar() { return AppBar( title: Text(AppLocalizations.of(context).weight), @@ -57,9 +52,7 @@ class _WeightScreenState extends State { ); }, ), - body: Consumer( - builder: (context, weightProvider, child) => WeightEntriesList(weightProvider), - ), + body: WeightEntriesList(), ); } @@ -67,7 +60,7 @@ class _WeightScreenState extends State { showModalBottomSheet( context: context, builder: (BuildContext ctx) { - return Container(margin: EdgeInsets.all(20), child: WeightForm()); + return WeightForm(); }, ); } diff --git a/lib/widgets/weight/entries_list.dart b/lib/widgets/weight/entries_list.dart index b97e25728..803a30f94 100644 --- a/lib/widgets/weight/entries_list.dart +++ b/lib/widgets/weight/entries_list.dart @@ -19,18 +19,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/weight/charts.dart'; import 'package:wger/widgets/weight/forms.dart'; class WeightEntriesList extends StatelessWidget { - final BodyWeight _weightProvider; - - WeightEntriesList(this._weightProvider); - @override Widget build(BuildContext context) { + final _weightProvider = Provider.of(context, listen: false); + return Column( children: [ Container( diff --git a/pubspec.lock b/pubspec.lock index 505caa441..38948fafb 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,14 +7,14 @@ packages: name: _fe_analyzer_shared url: "https://pub.dartlang.org" source: hosted - version: "17.0.0" + version: "18.0.0" analyzer: dependency: transitive description: name: analyzer url: "https://pub.dartlang.org" source: hosted - version: "1.1.0" + version: "1.2.0" android_metadata: dependency: "direct main" description: @@ -56,14 +56,14 @@ packages: name: build url: "https://pub.dartlang.org" source: hosted - version: "1.6.3" + version: "2.0.0" build_config: dependency: transitive description: name: build_config url: "https://pub.dartlang.org" source: hosted - version: "0.4.6" + version: "0.4.7" build_daemon: dependency: transitive description: @@ -77,21 +77,21 @@ packages: name: build_resolvers url: "https://pub.dartlang.org" source: hosted - version: "1.5.4" + version: "2.0.0" build_runner: dependency: "direct dev" description: name: build_runner url: "https://pub.dartlang.org" source: hosted - version: "1.11.5" + version: "1.12.2" build_runner_core: dependency: transitive description: name: build_runner_core url: "https://pub.dartlang.org" source: hosted - version: "6.1.10" + version: "6.1.12" built_collection: dependency: transitive description: @@ -105,7 +105,7 @@ packages: name: built_value url: "https://pub.dartlang.org" source: hosted - version: "8.0.2" + version: "8.0.3" characters: dependency: transitive description: @@ -140,7 +140,7 @@ packages: name: checked_yaml url: "https://pub.dartlang.org" source: hosted - version: "1.0.4" + version: "2.0.1" cli_util: dependency: transitive description: @@ -300,7 +300,7 @@ packages: name: graphs url: "https://pub.dartlang.org" source: hosted - version: "0.2.0" + version: "1.0.0" http: dependency: "direct main" description: @@ -314,7 +314,7 @@ packages: name: http_multi_server url: "https://pub.dartlang.org" source: hosted - version: "2.2.0" + version: "3.0.0" http_parser: dependency: transitive description: @@ -342,7 +342,7 @@ packages: name: io url: "https://pub.dartlang.org" source: hosted - version: "0.3.5" + version: "1.0.0" js: dependency: transitive description: @@ -363,7 +363,7 @@ packages: name: json_serializable url: "https://pub.dartlang.org" source: hosted - version: "4.0.2" + version: "4.0.3" logging: dependency: transitive description: @@ -398,7 +398,7 @@ packages: name: mockito url: "https://pub.dartlang.org" source: hosted - version: "5.0.1" + version: "5.0.2" nested: dependency: transitive description: @@ -510,14 +510,14 @@ packages: name: pubspec_parse url: "https://pub.dartlang.org" source: hosted - version: "0.1.8" + version: "1.0.0" shared_preferences: dependency: "direct main" description: name: shared_preferences url: "https://pub.dartlang.org" source: hosted - version: "2.0.4" + version: "2.0.5" shared_preferences_linux: dependency: transitive description: @@ -559,14 +559,14 @@ packages: name: shelf url: "https://pub.dartlang.org" source: hosted - version: "1.0.0" + version: "1.1.0" shelf_web_socket: dependency: transitive description: name: shelf_web_socket url: "https://pub.dartlang.org" source: hosted - version: "0.2.4+1" + version: "1.0.1" simple_gesture_detector: dependency: transitive description: @@ -585,7 +585,7 @@ packages: name: source_gen url: "https://pub.dartlang.org" source: hosted - version: "0.9.10+3" + version: "0.9.10+4" source_span: dependency: transitive description: @@ -648,7 +648,7 @@ packages: name: timing url: "https://pub.dartlang.org" source: hosted - version: "0.1.1+3" + version: "1.0.0" typed_data: dependency: transitive description: @@ -718,7 +718,7 @@ packages: name: web_socket_channel url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "2.0.0" win32: dependency: transitive description: diff --git a/test/auth_screen_test.dart b/test/auth_screen_test.dart index 221911ea3..cd09dd797 100644 --- a/test/auth_screen_test.dart +++ b/test/auth_screen_test.dart @@ -17,13 +17,50 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/providers/auth.dart'; import 'package:wger/screens/auth_screen.dart'; void main() { testWidgets('Test the widgets on the auth screen, login mode', (WidgetTester tester) async { // Wrap screen in material app so that the media query gets a context - await tester.pumpWidget(MaterialApp(home: AuthScreen())); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider( + create: (ctx) => Auth(), + ), + ], + child: Consumer( + builder: (ctx, auth, _) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('en'), + home: AuthScreen(), + ), + ), + ), + ); +/* + Provider( + create: (_) => Auth(), + // we use `builder` to obtain a new `BuildContext` that has access to the provider + builder: (context) { + // No longer throws + return Text(''), + } + ); + + */ + + Consumer( + builder: (ctx, auth, _) => MaterialApp( + builder: (ctx, authResultSnapshot) => AuthScreen(), + ), + ); + await tester.pumpAndSettle(); expect(find.text('WGER'), findsOneWidget); // Verify that the correct buttons and input fields are shown: login @@ -34,11 +71,14 @@ void main() { expect(find.byKey(Key('inputUsername')), findsOneWidget); expect(find.byKey(Key('inputEmail')), findsNothing); expect(find.byKey(Key('inputPassword')), findsOneWidget); - expect(find.byKey(Key('inputServer')), findsOneWidget); + expect(find.byKey(Key('inputServer')), findsNothing); expect(find.byKey(Key('inputPassword2')), findsNothing); expect(find.byKey(Key('actionButton')), findsOneWidget); expect(find.byKey(Key('toggleActionButton')), findsOneWidget); - }); + expect(find.byKey(Key('toggleCustomServerButton')), findsOneWidget); + }, skip: true); // TODO: skipped because of technical problems: + // either the provider wasn't found or, if the call was removed, the + // localization data could not be loaded... testWidgets('Test the widgets on the auth screen, registration', (WidgetTester tester) async { // Wrap screen in material app so that the media query gets a context @@ -58,5 +98,5 @@ void main() { expect(find.byKey(Key('inputPassword2')), findsOneWidget); expect(find.byKey(Key('actionButton')), findsOneWidget); expect(find.byKey(Key('toggleActionButton')), findsOneWidget); - }); + }, skip: true); } diff --git a/test/weight_model_test.dart b/test/weight_model_test.dart index 381b7efd3..6e17a1682 100644 --- a/test/weight_model_test.dart +++ b/test/weight_model_test.dart @@ -41,4 +41,16 @@ void main() { expect(weightEntry.date, weightEntryObj.date); }); }); + + group('model', () { + test('Test the individual values from the model', () { + WeightEntry _weightModel; + _weightModel = WeightEntry(); + _weightModel = WeightEntry(id: 1, weight: 80, date: DateTime(2020, 10, 01)); + + expect(_weightModel.id, 1); + expect(_weightModel.weight, 80); + expect(_weightModel.date, DateTime(2020, 10, 01)); + }); + }); } diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart new file mode 100644 index 000000000..6175aa923 --- /dev/null +++ b/test/weight_screen_test.dart @@ -0,0 +1,66 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (C) 2020 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * wger Workout Manager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/models/body_weight/weight_entry.dart'; +import 'package:wger/providers/body_weight.dart'; +import 'package:wger/screens/weight_screen.dart'; +import 'package:wger/widgets/weight/charts.dart'; +import 'package:wger/widgets/weight/forms.dart'; + +import 'utils.dart'; + +void main() { + Widget createHomeScreen() => ChangeNotifierProvider( + create: (context) => BodyWeight( + testAuth, + [ + WeightEntry(id: 1, weight: 80, date: DateTime(2021, 01, 01)), + WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)), + ], + ), + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + locale: Locale('en'), + //home: WeightEntriesList(), + home: WeightScreen(), + ), + ); + + testWidgets('Test the widgets on the body weight screen', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + //debugDumpApp(); + expect(find.text('Weight'), findsOneWidget); + expect(find.byType(WeightChartWidget), findsOneWidget); + expect(find.byType(Dismissible), findsNWidgets(2)); + expect(find.byType(ListTile), findsNWidgets(2)); + }); + + testWidgets('Test the form on the body weight screen', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + expect(find.byType(WeightForm), findsNothing); + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + expect(find.byType(WeightForm), findsOneWidget); + }); +} From 28c3a265bacc5f632baf788c798f2445b6250d49 Mon Sep 17 00:00:00 2001 From: Stefano Rossi Date: Thu, 18 Mar 2021 15:10:41 +0000 Subject: [PATCH 36/58] Translated using Weblate (Italian) Currently translated at 100.0% (83 of 83 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/it/ --- lib/l10n/app_it.arb | 271 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 270 insertions(+), 1 deletion(-) diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 0967ef424..681d38b28 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -1 +1,270 @@ -{} +{ + "anErrorOccurred": "È avvenuto un errore!", + "@anErrorOccurred": {}, + "selectIngredient": "Seleziona un ingrediente", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" + }, + "enterValidNumber": "Inserisci un numero valido", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "enterValue": "Inserisci un valore", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "goToToday": "Seleziona giorno", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "calendar": "Calendario", + "@calendar": {}, + "aboutText": "wger è rilasciato con \"permesso d'autore\", licenza AGPLv3+ e disponibile su GitHub:", + "@aboutText": { + "description": "Text in the about dialog" + }, + "toggleDetails": "Scegli dettagli", + "@toggleDetails": { + "description": "Switch to toggle detail / overview" + }, + "newNutritionalPlan": "Nuovo piano nutrizionale", + "@newNutritionalPlan": {}, + "confirmDelete": "Sei sicuro di voler cancellare '{toDelete}'?", + "@confirmDelete": { + "description": "Confirmation text before the user deletes an object", + "type": "text", + "placeholders": { + "toDelete": {} + } + }, + "delete": "Cancella", + "@delete": {}, + "loadingText": "Caricamento...", + "@loadingText": { + "description": "Text to show when entries are being loaded in the background: Loading..." + }, + "edit": "Modifica", + "@edit": {}, + "noWeightEntries": "Non hai nessun dato sul peso", + "@noWeightEntries": { + "description": "Message shown when the user has no logged weight entries" + }, + "newEntry": "Nuovo dato", + "@newEntry": { + "description": "Title when adding a new entry such as a weight or log entry" + }, + "unit": "Unità", + "@unit": { + "description": "The unit used for a repetition (kg, time, etc.)" + }, + "amount": "Quatità", + "@amount": { + "description": "The amount (e.g. in grams) of an ingredient in a meal" + }, + "sodium": "Sodio", + "@sodium": {}, + "fibres": "Fibre", + "@fibres": {}, + "saturatedFat": "Grassi saturi", + "@saturatedFat": {}, + "fat": "Grassi", + "@fat": {}, + "sugars": "Zuccheri", + "@sugars": {}, + "carbohydrates": "Carboidrati", + "@carbohydrates": {}, + "protein": "Proteine", + "@protein": {}, + "g": "g", + "@g": { + "description": "Abbreviation for gram" + }, + "kJ": "kJ", + "@kJ": { + "description": "Energy in a meal in kilo joules, kJ" + }, + "kcal": "kcal", + "@kcal": { + "description": "Energy in a meal in kilocalories, kcal" + }, + "energy": "Energia", + "@energy": { + "description": "Energy in a meal, ingredient etc. e.g. in kJ" + }, + "ingredient": "Ingrediente", + "@ingredient": {}, + "timeEnd": "Fine del tempo", + "@timeEnd": { + "description": "The end time of a workout" + }, + "timeStart": "Inizia cronometro", + "@timeStart": { + "description": "The starting time of a workout" + }, + "time": "Orario", + "@time": { + "description": "The time of a meal or workout" + }, + "date": "Data", + "@date": { + "description": "The date of a workout log or body weight entry" + }, + "weight": "Peso", + "@weight": { + "description": "The weight of a workout log or body weight entry" + }, + "dismiss": "Annulla", + "@dismiss": {}, + "noNutritionalPlans": "Non hai nessun piano nutrizionale", + "@noNutritionalPlans": { + "description": "Message shown when the user has no nutritional plans" + }, + "nutritionalPlans": "Piani nutrizionali", + "@nutritionalPlans": {}, + "nutritionalDiary": "Diario nutrizionale", + "@nutritionalDiary": {}, + "nutritionalPlan": "Piano nutrizionale", + "@nutritionalPlan": {}, + "addIngredient": "Aggiungi ingrediente", + "@addIngredient": {}, + "mealLogged": "Pasto registrato nel diario", + "@mealLogged": {}, + "addMeal": "Aggiungi pasto", + "@addMeal": {}, + "add": "Aggiungi", + "@add": {}, + "cancel": "Cancella", + "@cancel": {}, + "save": "Salva", + "@save": {}, + "description": "Descrizione", + "@description": {}, + "logHelpEntriesUnits": "Da notare che solo i dati con l'unità del peso (kg o lb) e le ripetizioni sono mostrate. Altre combinazioni come tempo o 'a cedimento' sono ignorate.", + "@logHelpEntriesUnits": {}, + "logHelpEntries": "Se in una giornata c'è più di esercizio con lo stesso numero di ripetizioni, ma con pesi differenti, solo l'esercizio con il peso più alto viene mostrato nel diagramma.", + "@logHelpEntries": {}, + "gymMode": "Modalità allenamento", + "@gymMode": { + "description": "Label when starting the gym mode" + }, + "newSet": "Nuova serie", + "@newSet": { + "description": "Header when adding a new set to a workout day" + }, + "newDay": "Nuovo giorno", + "@newDay": {}, + "workoutSession": "Sessione di allenamento", + "@workoutSession": { + "description": "A (logged) workout session" + }, + "notes": "Note", + "@notes": { + "description": "Personal notes, e.g. for a workout session" + }, + "impression": "Sensazione", + "@impression": { + "description": "General impression (e.g. for a workout session) such as good, bad, etc." + }, + "comment": "Commento", + "@comment": { + "description": "Comment, additional information" + }, + "rir": "RiR", + "@rir": { + "description": "Shorthand for Repetitions In Reserve" + }, + "repetitions": "Ripetizioni", + "@repetitions": { + "description": "Repetitions for an exercise set" + }, + "addExercise": "Aggiungi esercizi per questo giorno", + "@addExercise": {}, + "noWorkoutPlans": "Non hai nessun piano di allenamento", + "@noWorkoutPlans": { + "description": "Message shown when the user has no workout plans" + }, + "newWorkout": "Nuovo piano di allenamento", + "@newWorkout": { + "description": "Header when adding a new workout" + }, + "exercise": "Esercizio", + "@exercise": { + "description": "An exercise for a workout" + }, + "successfullyDeleted": "Cancellato", + "@successfullyDeleted": { + "description": "Message when an item was successfully deleted" + }, + "labelDashboard": "Pannello di controllo", + "@labelDashboard": { + "description": "Title for screen dashboard" + }, + "labelWorkoutPlan": "Piano di allenamento", + "@labelWorkoutPlan": { + "description": "Title for screen workout plan" + }, + "labelWorkoutPlans": "Piani di allenamento", + "@labelWorkoutPlans": { + "description": "Title for screen workout plans" + }, + "loginInstead": "Al log in", + "@loginInstead": {}, + "registerInstead": "Alla registrazione", + "@registerInstead": {}, + "reset": "Rerimposta", + "@reset": { + "description": "Button text allowing the user to reset the entered values to the default" + }, + "customServerHint": "Inserisci l'indirizzo del tuo server personale o quello predefinito verrà utilizzato", + "@customServerHint": { + "description": "Hint text for the form where the users can enter their own wger instance" + }, + "customServerUrl": "URL istanza wger", + "@customServerUrl": { + "description": "Label in the form where the users can enter their own wger instance" + }, + "invalidUsername": "Inserisci un nome utente valido", + "@invalidUsername": { + "description": "Error message when the user enters an invalid username" + }, + "username": "Nome utente", + "@username": {}, + "email": "Indirizzo e-mail", + "@email": {}, + "invalidEmail": "Inserisci un indirizzo e-mail valido", + "@invalidEmail": { + "description": "Error message when the user enters an invalid email" + }, + "confirmPassword": "Conferma password", + "@confirmPassword": {}, + "password": "Password", + "@password": {}, + "passwordTooShort": "La password è troppo corta", + "@passwordTooShort": { + "description": "Error message when the user a password that is too short" + }, + "passwordsDontMatch": "Le passwords non coincidono", + "@passwordsDontMatch": { + "description": "Error message when the user enters two different passwords during registration" + }, + "invalidUrl": "Inserisci un URL valido", + "@invalidUrl": { + "description": "Error message when the user enters an invalid URL, e.g. in the login form" + }, + "useCustomServer": "Usa un server personale", + "@useCustomServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "useDefaultServer": "Usa il server predefinito", + "@useDefaultServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "register": "Registrati", + "@register": { + "description": "Text for registration button" + }, + "login": "Entra", + "@login": { + "description": "Text for login button" + } +} From 3c02e0fca5b3dee696593abea37774db3d75491a Mon Sep 17 00:00:00 2001 From: Stefano Rossi Date: Thu, 18 Mar 2021 13:30:02 +0000 Subject: [PATCH 37/58] Translated using Weblate (Italian) Currently translated at 100.0% (4 of 4 strings) Translation: wger Workout Manager/Play Store Translate-URL: https://hosted.weblate.org/projects/wger/play-store/it/ --- android/fastlane/metadata/android/it/full_description.txt | 6 ++++++ android/fastlane/metadata/android/it/short_description.txt | 1 + 2 files changed, 7 insertions(+) create mode 100644 android/fastlane/metadata/android/it/full_description.txt create mode 100644 android/fastlane/metadata/android/it/short_description.txt diff --git a/android/fastlane/metadata/android/it/full_description.txt b/android/fastlane/metadata/android/it/full_description.txt new file mode 100644 index 000000000..143039a3a --- /dev/null +++ b/android/fastlane/metadata/android/it/full_description.txt @@ -0,0 +1,6 @@ +wger (ˈvɛɡɐ) è un software libero che aiuta la tua saluta + +- Pianifica allenamento e dieta +- Salva gli esercizi e aggiungi note +- modalità allenamento +- Diario e monitoraggio dello sviluppo diff --git a/android/fastlane/metadata/android/it/short_description.txt b/android/fastlane/metadata/android/it/short_description.txt new file mode 100644 index 000000000..3121b94ed --- /dev/null +++ b/android/fastlane/metadata/android/it/short_description.txt @@ -0,0 +1 @@ +Monitoraggio fitness/workout, dieta e peso From 9ea2a55ed64fe60fdd57b985b8f6c90f21b44415 Mon Sep 17 00:00:00 2001 From: Stefano Rossi Date: Thu, 18 Mar 2021 16:06:14 +0000 Subject: [PATCH 38/58] Translated using Weblate (French) Currently translated at 100.0% (4 of 4 strings) Translation: wger Workout Manager/Play Store Translate-URL: https://hosted.weblate.org/projects/wger/play-store/fr/ --- android/fastlane/metadata/android/fr/full_description.txt | 6 ++++++ android/fastlane/metadata/android/fr/short_description.txt | 1 + 2 files changed, 7 insertions(+) create mode 100644 android/fastlane/metadata/android/fr/full_description.txt create mode 100644 android/fastlane/metadata/android/fr/short_description.txt diff --git a/android/fastlane/metadata/android/fr/full_description.txt b/android/fastlane/metadata/android/fr/full_description.txt new file mode 100644 index 000000000..f7c527ca0 --- /dev/null +++ b/android/fastlane/metadata/android/fr/full_description.txt @@ -0,0 +1,6 @@ +Wger (Vɡɐɡɐ) est "copylified" logiciel libre qui aide votre santé. + +- Planifier les entraînements et le régime alimentaire +- Enregistrez des exercices et notes +- Mode entraînement +- Journal et suivi du développement diff --git a/android/fastlane/metadata/android/fr/short_description.txt b/android/fastlane/metadata/android/fr/short_description.txt new file mode 100644 index 000000000..5fd20302c --- /dev/null +++ b/android/fastlane/metadata/android/fr/short_description.txt @@ -0,0 +1 @@ +Fitness / entraînement, nutrition et tracker de poids From eef39b5ace7f35b680d07bc8a1bf96f8ebd2d519 Mon Sep 17 00:00:00 2001 From: Stefano Rossi Date: Thu, 18 Mar 2021 16:56:57 +0000 Subject: [PATCH 39/58] Translated using Weblate (French) Currently translated at 100.0% (83 of 83 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/fr/ --- lib/l10n/app_fr.arb | 271 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 270 insertions(+), 1 deletion(-) diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 0967ef424..971ec5677 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1 +1,270 @@ -{} +{ + "logHelpEntries": "Si durant une journée il y à plusieurs données avec le même nombre de répétitions, mais avec un poids différent, seulement les données avec le poids le plus haut sera affiché.", + "@logHelpEntries": {}, + "logHelpEntriesUnits": "Noter que seulement les données avec l'unité du poids (kg ou lb) et les répétitions seront affiché, autres combinaisons comme temps ou \"au échec\" sont ignorées.", + "@logHelpEntriesUnits": {}, + "weight": "Poids", + "@weight": { + "description": "The weight of a workout log or body weight entry" + }, + "confirmDelete": "Ês-tu sûr de vouloir supprimer '{toDelete}'?", + "@confirmDelete": { + "description": "Confirmation text before the user deletes an object", + "type": "text", + "placeholders": { + "toDelete": {} + } + }, + "selectIngredient": "Sélectionner un ingrédient", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" + }, + "enterValidNumber": "Insérer un nombre valide", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "enterValue": "Insérer un valeur", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "goToToday": "Aller à aujourd'hui", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "calendar": "Calendrier", + "@calendar": {}, + "aboutText": "wger est un logiciel libre, sous licence AFPLv3+ et disponible sur GitHub:", + "@aboutText": { + "description": "Text in the about dialog" + }, + "toggleDetails": "Choisir les détailles", + "@toggleDetails": { + "description": "Switch to toggle detail / overview" + }, + "newNutritionalPlan": "Nouveau journal nutritionnel", + "@newNutritionalPlan": {}, + "delete": "Supprimer", + "@delete": {}, + "loadingText": "Chargement...", + "@loadingText": { + "description": "Text to show when entries are being loaded in the background: Loading..." + }, + "edit": "Modifier", + "@edit": {}, + "noWeightEntries": "Aucune entrée de poids", + "@noWeightEntries": { + "description": "Message shown when the user has no logged weight entries" + }, + "newEntry": "Nouvelle entrée", + "@newEntry": { + "description": "Title when adding a new entry such as a weight or log entry" + }, + "unit": "Unité", + "@unit": { + "description": "The unit used for a repetition (kg, time, etc.)" + }, + "amount": "Quantité", + "@amount": { + "description": "The amount (e.g. in grams) of an ingredient in a meal" + }, + "sodium": "Sodium", + "@sodium": {}, + "fibres": "Fibres", + "@fibres": {}, + "saturatedFat": "Graisses saturées", + "@saturatedFat": {}, + "fat": "Graisses", + "@fat": {}, + "sugars": "Sucres", + "@sugars": {}, + "carbohydrates": "Glucides", + "@carbohydrates": {}, + "protein": "Protéines", + "@protein": {}, + "g": "g", + "@g": { + "description": "Abbreviation for gram" + }, + "kJ": "kJ", + "@kJ": { + "description": "Energy in a meal in kilo joules, kJ" + }, + "kcal": "kcal", + "@kcal": { + "description": "Energy in a meal in kilocalories, kcal" + }, + "energy": "Energie", + "@energy": { + "description": "Energy in a meal, ingredient etc. e.g. in kJ" + }, + "ingredient": "Ingrédient", + "@ingredient": {}, + "timeEnd": "Horaire de fin", + "@timeEnd": { + "description": "The end time of a workout" + }, + "timeStart": "Horaire de départ", + "@timeStart": { + "description": "The starting time of a workout" + }, + "time": "Oraire", + "@time": { + "description": "The time of a meal or workout" + }, + "date": "Date", + "@date": { + "description": "The date of a workout log or body weight entry" + }, + "dismiss": "Rejeter", + "@dismiss": {}, + "anErrorOccurred": "La dernière action a échouée!", + "@anErrorOccurred": {}, + "noNutritionalPlans": "Aucune plan nutritionnel", + "@noNutritionalPlans": { + "description": "Message shown when the user has no nutritional plans" + }, + "nutritionalPlans": "Plan nutritionnel", + "@nutritionalPlans": {}, + "nutritionalDiary": "Journal nutritionnel", + "@nutritionalDiary": {}, + "nutritionalPlan": "Plan nutritionnel", + "@nutritionalPlan": {}, + "addIngredient": "Ajouter ingrédients", + "@addIngredient": {}, + "mealLogged": "Repas enregistré", + "@mealLogged": {}, + "addMeal": "Ajouter repas", + "@addMeal": {}, + "add": "Ajouter", + "@add": {}, + "cancel": "Supprimer", + "@cancel": {}, + "save": "Sauvegarder", + "@save": {}, + "description": "Description", + "@description": {}, + "gymMode": "Mode entraînement", + "@gymMode": { + "description": "Label when starting the gym mode" + }, + "newSet": "Nouvelle sèrie", + "@newSet": { + "description": "Header when adding a new set to a workout day" + }, + "newDay": "Nouveau jurnée", + "@newDay": {}, + "workoutSession": "Session d' entraînement", + "@workoutSession": { + "description": "A (logged) workout session" + }, + "notes": "Notes", + "@notes": { + "description": "Personal notes, e.g. for a workout session" + }, + "impression": "Impression", + "@impression": { + "description": "General impression (e.g. for a workout session) such as good, bad, etc." + }, + "comment": "Commentaire", + "@comment": { + "description": "Comment, additional information" + }, + "rir": "RsR", + "@rir": { + "description": "Shorthand for Repetitions In Reserve" + }, + "repetitions": "Répetitions", + "@repetitions": { + "description": "Repetitions for an exercise set" + }, + "addExercise": "Ajoute un exercice à cet journée", + "@addExercise": {}, + "noWorkoutPlans": "Aucune plan d'entraînement", + "@noWorkoutPlans": { + "description": "Message shown when the user has no workout plans" + }, + "newWorkout": "Nouveau plan d'entraînement", + "@newWorkout": { + "description": "Header when adding a new workout" + }, + "exercise": "Exercices", + "@exercise": { + "description": "An exercise for a workout" + }, + "successfullyDeleted": "Supprimer", + "@successfullyDeleted": { + "description": "Message when an item was successfully deleted" + }, + "labelDashboard": "Accueil", + "@labelDashboard": { + "description": "Title for screen dashboard" + }, + "labelWorkoutPlan": "Plan d'entraînement", + "@labelWorkoutPlan": { + "description": "Title for screen workout plan" + }, + "labelWorkoutPlans": "Plans d'entraînement", + "@labelWorkoutPlans": { + "description": "Title for screen workout plans" + }, + "registerInstead": "Sinon, s'inscrire", + "@registerInstead": {}, + "loginInstead": "Sinon, se connecter", + "@loginInstead": {}, + "reset": "Réinitialiser", + "@reset": { + "description": "Button text allowing the user to reset the entered values to the default" + }, + "useCustomServer": "Utiliser serveur personnelle", + "@useCustomServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "customServerHint": "Insérer l'adresse de ton serveur personnelle, sinon le serveur de défaut sera utilisé", + "@customServerHint": { + "description": "Hint text for the form where the users can enter their own wger instance" + }, + "customServerUrl": "URL de l'instance wger", + "@customServerUrl": { + "description": "Label in the form where the users can enter their own wger instance" + }, + "invalidUsername": "Insérer un nom utilisateur valide", + "@invalidUsername": { + "description": "Error message when the user enters an invalid username" + }, + "username": "Nom utilisateur", + "@username": {}, + "email": "Adresse e-mail", + "@email": {}, + "invalidEmail": "Insérer une adresse valide", + "@invalidEmail": { + "description": "Error message when the user enters an invalid email" + }, + "confirmPassword": "Confirmer le mot de passe", + "@confirmPassword": {}, + "password": "Mot de passe", + "@password": {}, + "passwordTooShort": "Le mot de passe est trop court", + "@passwordTooShort": { + "description": "Error message when the user a password that is too short" + }, + "passwordsDontMatch": "Les mots de passe sont différents", + "@passwordsDontMatch": { + "description": "Error message when the user enters two different passwords during registration" + }, + "invalidUrl": "Insérer une URL valide", + "@invalidUrl": { + "description": "Error message when the user enters an invalid URL, e.g. in the login form" + }, + "useDefaultServer": "Défaut serveur", + "@useDefaultServer": { + "description": "Toggle button allowing users to switch between the default and a custom wger server" + }, + "register": "Se inscrire", + "@register": { + "description": "Text for registration button" + }, + "login": "Se connecter", + "@login": { + "description": "Text for login button" + } +} From 1af8ab9ef49be1063397b0d079b39c68c7f4fb28 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 19 Mar 2021 10:02:07 +0100 Subject: [PATCH 40/58] Localize dates --- lib/widgets/dashboard/widgets.dart | 6 ++++-- lib/widgets/nutrition/nutritional_plans_list.dart | 5 ++++- lib/widgets/weight/entries_list.dart | 5 ++++- lib/widgets/workouts/workout_plans_list.dart | 5 ++++- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 20031f64b..5367a81d6 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -117,7 +117,8 @@ class _DashboardNutritionWidgetState extends State { ? Column( children: [ Text( - DateFormat.yMd().format(plan.creationDate), + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(plan.creationDate), style: Theme.of(context).textTheme.headline6, ), TextButton( @@ -292,7 +293,8 @@ class _DashboardWorkoutWidgetState extends State { ? Column( children: [ Text( - DateFormat.yMd().format(_workoutPlan.creationDate), + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(_workoutPlan.creationDate), style: Theme.of(context).textTheme.headline6, ), TextButton( diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index d79bee2b8..9784a2ff7 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -100,7 +100,10 @@ class NutritionalPlansList extends StatelessWidget { ); }, title: Text(currentPlan.description), - subtitle: Text(DateFormat.yMd().format(currentPlan.creationDate)), + subtitle: Text( + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(currentPlan.creationDate), + ), ), ), ); diff --git a/lib/widgets/weight/entries_list.dart b/lib/widgets/weight/entries_list.dart index 803a30f94..87d7a0050 100644 --- a/lib/widgets/weight/entries_list.dart +++ b/lib/widgets/weight/entries_list.dart @@ -102,7 +102,10 @@ class WeightEntriesList extends StatelessWidget { child: Card( child: ListTile( onTap: () {}, - title: Text(DateFormat.yMd().format(currentEntry.date).toString()), + title: Text( + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(currentEntry.date), + ), subtitle: Text('${currentEntry.weight} kg'), ), ), diff --git a/lib/widgets/workouts/workout_plans_list.dart b/lib/widgets/workouts/workout_plans_list.dart index aa06aaf4f..160e720d1 100644 --- a/lib/widgets/workouts/workout_plans_list.dart +++ b/lib/widgets/workouts/workout_plans_list.dart @@ -103,7 +103,10 @@ class WorkoutPlansList extends StatelessWidget { .pushNamed(WorkoutPlanScreen.routeName, arguments: currentWorkout); }, title: Text(currentWorkout.description), - subtitle: Text(DateFormat.yMd().format(currentWorkout.creationDate)), + subtitle: Text( + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(currentWorkout.creationDate), + ), ), ), ); From c6228ec048857174bb954fc690e3aa8a19845517 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 19 Mar 2021 10:22:52 +0100 Subject: [PATCH 41/58] Add more tests for the body weight screen --- test/weight_screen_test.dart | 69 ++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 15 deletions(-) diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart index 6175aa923..b24362885 100644 --- a/test/weight_screen_test.dart +++ b/test/weight_screen_test.dart @@ -19,6 +19,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:mockito/mockito.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/body_weight.dart'; @@ -29,21 +31,36 @@ import 'package:wger/widgets/weight/forms.dart'; import 'utils.dart'; void main() { - Widget createHomeScreen() => ChangeNotifierProvider( - create: (context) => BodyWeight( - testAuth, - [ - WeightEntry(id: 1, weight: 80, date: DateTime(2021, 01, 01)), - WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)), - ], - ), - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - locale: Locale('en'), - //home: WeightEntriesList(), - home: WeightScreen(), - ), - ); + Widget createHomeScreen({locale = 'en'}) { + final client = MockClient(); + when(client.delete( + any, + headers: anyNamed('headers'), + )).thenAnswer((_) async => http.Response('', 200)); + when(client.post( + any, + headers: anyNamed('headers'), + body: anyNamed('body'), + )).thenAnswer( + (_) async => http.Response('{"id": 3, "date": "2021-01-01", "weight": "80"}', 200)); + + return ChangeNotifierProvider( + create: (context) => BodyWeight( + testAuth, + [ + WeightEntry(id: 1, weight: 80, date: DateTime(2021, 01, 01)), + WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)), + ], + client, + ), + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: WeightScreen(), + ), + ); + } testWidgets('Test the widgets on the body weight screen', (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); @@ -55,6 +72,14 @@ void main() { expect(find.byType(ListTile), findsNWidgets(2)); }); + testWidgets('Test deleting an item by dragging the dismissible', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + await tester.drag(find.byKey(Key('1')), Offset(-500.0, 0.0)); + await tester.pumpAndSettle(); + expect(find.byType(ListTile), findsOneWidget); + }); + testWidgets('Test the form on the body weight screen', (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); @@ -63,4 +88,18 @@ void main() { await tester.pumpAndSettle(); expect(find.byType(WeightForm), findsOneWidget); }); + + testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + expect(find.text('1/1/2021'), findsOneWidget); + expect(find.text('1/10/2021'), findsOneWidget); + }); + + testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen(locale: 'de')); + + expect(find.text('1.1.2021'), findsOneWidget); + expect(find.text('10.1.2021'), findsOneWidget); + }); } From ab974aab8611b4399a2a0e341bc5dc8204b07725 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 19 Mar 2021 23:41:04 +0100 Subject: [PATCH 42/58] Move computed settings to set loop Format of REST API changed in server --- lib/providers/workout_plans.dart | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index 764292911..5414528ff 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -144,10 +144,10 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { List days = []; for (final entry in data['day_list']) { List sets = []; + List settingsComputed = []; for (final set in entry['set_list']) { List settings = []; - List settingsComputed = []; List exercises = []; for (final exerciseData in set['exercise_list']) { @@ -188,11 +188,11 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { ), ); } + } - // Computed settings - for (var setting in exerciseData['settings_computed']) { - settingsComputed.add(Setting.fromJson(setting)); - } + // Computed settings + for (var setting in set['settings_computed']) { + settingsComputed.add(Setting.fromJson(setting)); } // Sets From 64d6e85e4833d44423ba3dc8ce19b3e391dbbe29 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 19 Mar 2021 23:41:31 +0100 Subject: [PATCH 43/58] Show the body weight as the title That is probably more important than the date --- lib/widgets/weight/entries_list.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/widgets/weight/entries_list.dart b/lib/widgets/weight/entries_list.dart index 87d7a0050..8cb1d2d12 100644 --- a/lib/widgets/weight/entries_list.dart +++ b/lib/widgets/weight/entries_list.dart @@ -102,11 +102,11 @@ class WeightEntriesList extends StatelessWidget { child: Card( child: ListTile( onTap: () {}, - title: Text( + title: Text('${currentEntry.weight} kg'), + subtitle: Text( DateFormat.yMd(Localizations.localeOf(context).languageCode) .format(currentEntry.date), ), - subtitle: Text('${currentEntry.weight} kg'), ), ), ); From 5b06a86576dcb39d666c654f360e5abdb09a2e0a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 20 Mar 2021 00:05:16 +0100 Subject: [PATCH 44/58] Add overflow behaviour for workout day descriptions --- lib/widgets/workouts/day.dart | 59 +++++++++++++++++------------------ 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index c89ecf165..778f5fa2a 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -192,38 +192,37 @@ class DayHeaderDismissible extends StatelessWidget { padding: const EdgeInsets.all(10), decoration: BoxDecoration(color: Colors.white), child: Row( - //mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _day.description, - style: Theme.of(context).textTheme.headline5, - ), - Text(_day.getDaysText), - ], + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _day.description, + style: Theme.of(context).textTheme.headline5, + overflow: TextOverflow.ellipsis, + ), + Text(_day.getDaysText), + ], + ), ), - Expanded(child: Container()), - /* - if (_expanded) - IconButton( - icon: Icon(Icons.edit), - onPressed: () {}, - ), - */ - if (_expanded) - IconButton( - icon: Icon(Icons.delete), - onPressed: () { - Provider.of(context, listen: false).deleteDay(_day); - }, - ), - IconButton( - icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more), - onPressed: () { - _toggle(); - }, + Row( + children: [ + if (_expanded) + IconButton( + icon: Icon(Icons.delete), + onPressed: () { + Provider.of(context, listen: false).deleteDay(_day); + }, + ), + IconButton( + icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more), + onPressed: () { + _toggle(); + }, + ), + ], ), ], ), From ecd2773a871915b764e7a3cd2e9fda9d84ffd19c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 22 Mar 2021 12:30:52 +0100 Subject: [PATCH 45/58] Upgrade packages and move application to null safety --- android/fastlane/README.md | 6 +- android/fastlane/report.xml | 4 +- lib/helpers/consts.dart | 8 +- lib/helpers/json.dart | 21 +- lib/helpers/ui.dart | 16 +- lib/main.dart | 8 +- lib/models/body_weight/weight_entry.dart | 18 +- lib/models/body_weight/weight_entry.g.dart | 6 +- lib/models/exercises/category.dart | 4 +- lib/models/exercises/comment.dart | 4 +- lib/models/exercises/equipment.dart | 5 +- lib/models/exercises/exercise.dart | 37 ++-- lib/models/exercises/exercise.g.dart | 62 +++--- lib/models/exercises/image.dart | 4 +- lib/models/exercises/image.g.dart | 2 +- lib/models/exercises/muscle.dart | 6 +- lib/models/http_exception.dart | 4 +- lib/models/nutrition/ingredient.dart | 23 ++- lib/models/nutrition/ingredient.g.dart | 18 +- .../nutrition/ingredient_weight_unit.dart | 11 +- .../nutrition/ingredient_weight_unit.g.dart | 11 +- lib/models/nutrition/log.dart | 44 +++-- lib/models/nutrition/log.g.dart | 16 +- lib/models/nutrition/meal.dart | 22 ++- lib/models/nutrition/meal.g.dart | 16 +- lib/models/nutrition/meal_item.dart | 49 ++--- lib/models/nutrition/meal_item.g.dart | 14 +- lib/models/nutrition/nutritional_plan.dart | 17 +- lib/models/nutrition/nutritional_plan.g.dart | 18 +- lib/models/nutrition/weight_unit.dart | 5 +- lib/models/workouts/day.dart | 28 +-- lib/models/workouts/day.g.dart | 20 +- lib/models/workouts/log.dart | 38 ++-- lib/models/workouts/log.g.dart | 21 +- lib/models/workouts/repetition_unit.dart | 5 +- lib/models/workouts/session.dart | 32 +-- lib/models/workouts/session.g.dart | 17 +- lib/models/workouts/set.dart | 26 ++- lib/models/workouts/set.g.dart | 28 +-- lib/models/workouts/setting.dart | 53 ++--- lib/models/workouts/setting.g.dart | 30 ++- lib/models/workouts/weight_unit.dart | 4 +- lib/models/workouts/workout_plan.dart | 22 ++- lib/models/workouts/workout_plan.g.dart | 22 +-- lib/providers/auth.dart | 32 +-- lib/providers/base_provider.dart | 10 +- lib/providers/body_weight.dart | 3 +- lib/providers/exercises.dart | 9 +- lib/providers/helpers.dart | 8 +- lib/providers/nutrition.dart | 46 +++-- lib/providers/workout_plans.dart | 187 +++++++++--------- lib/screens/auth_screen.dart | 76 ++++--- lib/screens/dashboard.dart | 8 +- lib/screens/gym_mode.dart | 2 +- lib/screens/home_tabs_screen.dart | 2 +- lib/screens/nutritional_plan_screen.dart | 10 +- lib/screens/nutritional_plans_screen.dart | 9 +- lib/screens/weight_screen.dart | 6 +- lib/screens/workout_plan_screen.dart | 12 +- lib/screens/workout_plans_screen.dart | 11 +- lib/widgets/app_drawer.dart | 6 +- lib/widgets/core/bottom_sheet.dart | 2 +- lib/widgets/core/core.dart | 19 +- lib/widgets/dashboard/calendar.dart | 28 +-- lib/widgets/dashboard/widgets.dart | 69 ++++--- lib/widgets/nutrition/charts.dart | 25 +-- lib/widgets/nutrition/forms.dart | 142 ++++++++----- lib/widgets/nutrition/meal.dart | 38 ++-- .../nutrition/nutritional_plan_detail.dart | 50 ++--- .../nutrition/nutritional_plans_list.dart | 12 +- lib/widgets/weight/entries_list.dart | 4 +- lib/widgets/weight/forms.dart | 28 +-- lib/widgets/workouts/day.dart | 24 ++- lib/widgets/workouts/exercises.dart | 7 +- lib/widgets/workouts/forms.dart | 142 +++++++------ lib/widgets/workouts/gym_mode.dart | 53 +++-- lib/widgets/workouts/log.dart | 87 ++++---- lib/widgets/workouts/workout_logs.dart | 4 +- lib/widgets/workouts/workout_plan_detail.dart | 6 +- lib/widgets/workouts/workout_plans_list.dart | 14 +- pubspec.lock | 34 ++-- pubspec.yaml | 7 +- test/weight_model_test.dart | 2 +- test/weight_screen_test.dart | 4 +- 84 files changed, 1073 insertions(+), 990 deletions(-) diff --git a/android/fastlane/README.md b/android/fastlane/README.md index af8ee779b..18f05e093 100644 --- a/android/fastlane/README.md +++ b/android/fastlane/README.md @@ -24,11 +24,11 @@ fastlane playstore ---- ## Android -### android updateclosed_beta +### android updateclosed_alpha ``` -fastlane android updateclosed_beta +fastlane android updateclosed_alpha ``` -Update store entry +Upload closed alpha app and update store entry ### android test ``` fastlane android test diff --git a/android/fastlane/report.xml b/android/fastlane/report.xml index 9407b5625..36206176d 100644 --- a/android/fastlane/report.xml +++ b/android/fastlane/report.xml @@ -5,12 +5,12 @@ - + - + diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index d6e113ec1..293583190 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -21,5 +21,11 @@ const double ICON_SIZE_SMALL = 20; /// Default wger server during login -final DEFAULT_SERVER = 'https://wger.rge.uber.space'; +const DEFAULT_SERVER = 'https://wger.rge.uber.space'; //final DEFAULT_SERVER = 'http://localhost:8000'; + +/// Default weight unit is "kg" +const DEFAULT_WEIGHT_UNIT = 1; + +/// Default weight unit is "repetition" +const DEFAULT_REPETITION_UNIT = 1; diff --git a/lib/helpers/json.dart b/lib/helpers/json.dart index 0eaa92819..c6d8e2053 100644 --- a/lib/helpers/json.dart +++ b/lib/helpers/json.dart @@ -19,14 +19,11 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -num toNum(String e) { - if (e == null) { - return null; - } - return num.parse(e); +num toNum(String? e) { + return e == null ? 0 : num.parse(e); } -String toString(num e) { +String? toString(num? e) { if (e == null) { return null; } @@ -38,7 +35,7 @@ String toString(num e) { * Converts a datetime to ISO8601 date format, but only the date. * Needed e.g. when the wger api only expects a date and no time information. */ -String toDate(DateTime dateTime) { +String? toDate(DateTime? dateTime) { if (dateTime == null) { return null; } @@ -49,19 +46,17 @@ String toDate(DateTime dateTime) { * Converts a time to a date object. * Needed e.g. when the wger api only sends a time but no date information. */ -TimeOfDay stringToTime(String time) { - if (time == null) { - return null; - } +TimeOfDay stringToTime(String? time) { + String out = time ?? '00:00'; return TimeOfDay.fromDateTime( - DateTime.parse('2020-01-01 $time'), + DateTime.parse('2020-01-01 $out'), ); } /* * Converts a datetime to time. */ -String timeToString(TimeOfDay time) { +String? timeToString(TimeOfDay? time) { if (time == null) { return null; } diff --git a/lib/helpers/ui.dart b/lib/helpers/ui.dart index e7389ab41..c6ae1e976 100644 --- a/lib/helpers/ui.dart +++ b/lib/helpers/ui.dart @@ -30,11 +30,11 @@ void showErrorDialog(dynamic exception, BuildContext context) { showDialog( context: context, builder: (ctx) => AlertDialog( - title: Text(AppLocalizations.of(context).anErrorOccurred), + title: Text(AppLocalizations.of(context)!.anErrorOccurred), content: Text(exception.toString()), actions: [ TextButton( - child: Text(AppLocalizations.of(context).dismiss), + child: Text(AppLocalizations.of(context)!.dismiss), onPressed: () { Navigator.of(ctx).pop(); }, @@ -50,15 +50,15 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, BuildContext cont log('-------------------'); List errorList = []; - for (var key in exception.errors.keys) { + for (var key in exception.errors!.keys) { // Error headers errorList.add(Text(key, style: TextStyle(fontWeight: FontWeight.bold))); // Error messages - if (exception.errors[key] is String) { - errorList.add(Text(exception.errors[key])); + if (exception.errors![key] is String) { + errorList.add(Text(exception.errors![key])); } else { - for (var value in exception.errors[key]) { + for (var value in exception.errors![key]) { errorList.add(Text(value)); } } @@ -67,7 +67,7 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, BuildContext cont showDialog( context: context, builder: (ctx) => AlertDialog( - title: Text(AppLocalizations.of(context).anErrorOccurred), + title: Text(AppLocalizations.of(context)!.anErrorOccurred), content: Container( child: Column( mainAxisSize: MainAxisSize.min, @@ -76,7 +76,7 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, BuildContext cont ), actions: [ TextButton( - child: Text(AppLocalizations.of(context).dismiss), + child: Text(AppLocalizations.of(context)!.dismiss), onPressed: () { Navigator.of(ctx).pop(); }, diff --git a/lib/main.dart b/lib/main.dart index d46498107..80be03cff 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -51,28 +51,28 @@ class MyApp extends StatelessWidget { create: (ctx) => Auth(), ), ChangeNotifierProxyProvider( - create: null, // TODO: Create is required but it can be null?? + create: (context) => WorkoutPlans(Auth(), []), update: (context, auth, previous) => WorkoutPlans( auth, previous == null ? [] : previous.items, ), ), ChangeNotifierProxyProvider( - create: null, // TODO: Create is required but it can be null?? + create: (context) => Exercises(Auth(), []), update: (context, auth, previous) => Exercises( auth, previous == null ? [] : previous.items, ), ), ChangeNotifierProxyProvider( - create: null, // TODO: Create is required but it can be null?? + create: (context) => Nutrition(Auth(), []), update: (context, auth, previous) => Nutrition( auth, previous == null ? [] : previous.items, ), ), ChangeNotifierProxyProvider( - create: null, // TODO: Create is required but it can be null?? + create: (context) => BodyWeight(Auth(), []), update: (context, auth, previous) => BodyWeight( auth, previous == null ? [] : previous.items, diff --git a/lib/models/body_weight/weight_entry.dart b/lib/models/body_weight/weight_entry.dart index b9a0c3a30..bcc2a6900 100644 --- a/lib/models/body_weight/weight_entry.dart +++ b/lib/models/body_weight/weight_entry.dart @@ -24,19 +24,25 @@ part 'weight_entry.g.dart'; @JsonSerializable() class WeightEntry { @JsonKey(required: true) - final int id; + int? id; @JsonKey(required: true, fromJson: toNum, toJson: toString) - num weight; + late num weight; @JsonKey(required: true, toJson: toDate) - DateTime date; + late DateTime date; WeightEntry({ this.id, - this.weight, - this.date, - }); + weight, + DateTime? date, + }) { + this.date = date ?? DateTime.now(); + + if (weight != null) { + this.weight = weight; + } + } // Boilerplate factory WeightEntry.fromJson(Map json) => _$WeightEntryFromJson(json); diff --git a/lib/models/body_weight/weight_entry.g.dart b/lib/models/body_weight/weight_entry.g.dart index ac56a8f6d..4113a23e2 100644 --- a/lib/models/body_weight/weight_entry.g.dart +++ b/lib/models/body_weight/weight_entry.g.dart @@ -9,9 +9,9 @@ part of 'weight_entry.dart'; WeightEntry _$WeightEntryFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'weight', 'date']); return WeightEntry( - id: json['id'] as int, - weight: toNum(json['weight'] as String), - date: json['date'] == null ? null : DateTime.parse(json['date'] as String), + id: json['id'] as int?, + weight: toNum(json['weight'] as String?), + date: DateTime.parse(json['date'] as String), ); } diff --git a/lib/models/exercises/category.dart b/lib/models/exercises/category.dart index 23f15402e..6f93e46e3 100644 --- a/lib/models/exercises/category.dart +++ b/lib/models/exercises/category.dart @@ -29,8 +29,8 @@ class ExerciseCategory { final String name; ExerciseCategory({ - this.id, - this.name, + required this.id, + required this.name, }); @override diff --git a/lib/models/exercises/comment.dart b/lib/models/exercises/comment.dart index e2965f518..8c242300f 100644 --- a/lib/models/exercises/comment.dart +++ b/lib/models/exercises/comment.dart @@ -29,8 +29,8 @@ class Comment { final String comment; Comment({ - this.id, - this.comment, + required this.id, + required this.comment, }); // Boilerplate diff --git a/lib/models/exercises/equipment.dart b/lib/models/exercises/equipment.dart index e826ecfdf..f56bbf56c 100644 --- a/lib/models/exercises/equipment.dart +++ b/lib/models/exercises/equipment.dart @@ -16,7 +16,6 @@ * along with this program. If not, see . */ -import 'package:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; part 'equipment.g.dart'; @@ -30,8 +29,8 @@ class Equipment { final String name; Equipment({ - @required this.id, - @required this.name, + required this.id, + required this.name, }); // Boilerplate diff --git a/lib/models/exercises/exercise.dart b/lib/models/exercises/exercise.dart index d374e5d91..1bda09ddc 100644 --- a/lib/models/exercises/exercise.dart +++ b/lib/models/exercises/exercise.dart @@ -42,8 +42,11 @@ class Exercise { @JsonKey(required: true) final String description; - @JsonKey(required: true) - final ExerciseCategory category; + @JsonKey(required: false) + final int categoryId; + + @JsonKey(required: true, name: 'category') + late final ExerciseCategory categoryObj; @JsonKey(required: true) List muscles = []; @@ -61,18 +64,24 @@ class Exercise { List tips = []; Exercise({ - this.id, - this.uuid, - this.creationDate, - this.name, - this.description, - this.category, - this.muscles, - this.musclesSecondary, - this.equipment, - this.images, - this.tips, - }); + required this.id, + required this.uuid, + required this.creationDate, + required this.name, + required this.description, + required this.categoryId, + List? muscles, + List? musclesSecondary, + List? equipment, + List? images, + List? tips, + }) { + this.tips = tips ?? []; + this.images = images ?? []; + this.equipment = equipment ?? []; + this.musclesSecondary = musclesSecondary ?? []; + this.muscles = muscles ?? []; + } ExerciseImage get getMainImage { return images.firstWhere((image) => image.isMain); diff --git a/lib/models/exercises/exercise.g.dart b/lib/models/exercises/exercise.g.dart index 5746cb194..2ac8fe7a8 100644 --- a/lib/models/exercises/exercise.g.dart +++ b/lib/models/exercises/exercise.g.dart @@ -23,49 +23,41 @@ Exercise _$ExerciseFromJson(Map json) { return Exercise( id: json['id'] as int, uuid: json['uuid'] as String, - creationDate: json['creation_date'] == null - ? null - : DateTime.parse(json['creation_date'] as String), + creationDate: DateTime.parse(json['creation_date'] as String), name: json['name'] as String, description: json['description'] as String, - category: json['category'] == null - ? null - : ExerciseCategory.fromJson(json['category'] as Map), - muscles: (json['muscles'] as List) - ?.map((e) => - e == null ? null : Muscle.fromJson(e as Map)) - ?.toList(), - musclesSecondary: (json['muscles_secondary'] as List) - ?.map((e) => - e == null ? null : Muscle.fromJson(e as Map)) - ?.toList(), - equipment: (json['equipment'] as List) - ?.map((e) => - e == null ? null : Equipment.fromJson(e as Map)) - ?.toList(), - images: (json['images'] as List) - ?.map((e) => e == null - ? null - : ExerciseImage.fromJson(e as Map)) - ?.toList(), - tips: (json['comments'] as List) - ?.map((e) => - e == null ? null : Comment.fromJson(e as Map)) - ?.toList(), - ); + categoryId: json['categoryId'] as int, + muscles: (json['muscles'] as List?) + ?.map((e) => Muscle.fromJson(e as Map)) + .toList(), + musclesSecondary: (json['muscles_secondary'] as List?) + ?.map((e) => Muscle.fromJson(e as Map)) + .toList(), + equipment: (json['equipment'] as List?) + ?.map((e) => Equipment.fromJson(e as Map)) + .toList(), + images: (json['images'] as List?) + ?.map((e) => ExerciseImage.fromJson(e as Map)) + .toList(), + tips: (json['comments'] as List?) + ?.map((e) => Comment.fromJson(e as Map)) + .toList(), + )..categoryObj = + ExerciseCategory.fromJson(json['category'] as Map); } Map _$ExerciseToJson(Exercise instance) => { 'id': instance.id, 'uuid': instance.uuid, - 'creation_date': instance.creationDate?.toIso8601String(), + 'creation_date': instance.creationDate.toIso8601String(), 'name': instance.name, 'description': instance.description, - 'category': instance.category?.toJson(), - 'muscles': instance.muscles?.map((e) => e?.toJson())?.toList(), + 'categoryId': instance.categoryId, + 'category': instance.categoryObj.toJson(), + 'muscles': instance.muscles.map((e) => e.toJson()).toList(), 'muscles_secondary': - instance.musclesSecondary?.map((e) => e?.toJson())?.toList(), - 'equipment': instance.equipment?.map((e) => e?.toJson())?.toList(), - 'images': instance.images?.map((e) => e?.toJson())?.toList(), - 'comments': instance.tips?.map((e) => e?.toJson())?.toList(), + instance.musclesSecondary.map((e) => e.toJson()).toList(), + 'equipment': instance.equipment.map((e) => e.toJson()).toList(), + 'images': instance.images.map((e) => e.toJson()).toList(), + 'comments': instance.tips.map((e) => e.toJson()).toList(), }; diff --git a/lib/models/exercises/image.dart b/lib/models/exercises/image.dart index c13a9c1ab..227c6614f 100644 --- a/lib/models/exercises/image.dart +++ b/lib/models/exercises/image.dart @@ -29,8 +29,8 @@ class ExerciseImage { final bool isMain; ExerciseImage({ - this.url, - this.isMain, + required this.url, + required this.isMain, }); // Boilerplate diff --git a/lib/models/exercises/image.g.dart b/lib/models/exercises/image.g.dart index 6df8b7905..320f883e3 100644 --- a/lib/models/exercises/image.g.dart +++ b/lib/models/exercises/image.g.dart @@ -10,7 +10,7 @@ ExerciseImage _$ExerciseImageFromJson(Map json) { $checkKeys(json, requiredKeys: const ['image']); return ExerciseImage( url: json['image'] as String, - isMain: json['is_main'] as bool ?? false, + isMain: json['is_main'] as bool? ?? false, ); } diff --git a/lib/models/exercises/muscle.dart b/lib/models/exercises/muscle.dart index 298befe18..f4ddb82f5 100644 --- a/lib/models/exercises/muscle.dart +++ b/lib/models/exercises/muscle.dart @@ -32,9 +32,9 @@ class Muscle { final bool isFront; Muscle({ - this.id, - this.name, - this.isFront, + required this.id, + required this.name, + required this.isFront, }); // Boilerplate diff --git a/lib/models/http_exception.dart b/lib/models/http_exception.dart index 8bb022016..e6a018b11 100644 --- a/lib/models/http_exception.dart +++ b/lib/models/http_exception.dart @@ -19,7 +19,7 @@ import 'dart:convert'; class WgerHttpException implements Exception { - Map errors; + Map? errors; /// Custom http exception. /// Expects the response body of the REST call and will try to parse it to @@ -39,6 +39,6 @@ class WgerHttpException implements Exception { @override String toString() { - return errors.values.toList().join(', '); + return errors!.values.toList().join(', '); } } diff --git a/lib/models/nutrition/ingredient.dart b/lib/models/nutrition/ingredient.dart index a33219b2b..54d723866 100644 --- a/lib/models/nutrition/ingredient.dart +++ b/lib/models/nutrition/ingredient.dart @@ -16,7 +16,6 @@ * along with this program. If not, see . */ -import 'package:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wger/helpers/json.dart'; @@ -58,17 +57,17 @@ class Ingredient { final num sodium; Ingredient({ - @required this.id, - @required this.name, - @required this.creationDate, - @required this.energy, - @required this.carbohydrates, - @required this.carbohydratesSugar, - @required this.protein, - @required this.fat, - @required this.fatSaturated, - @required this.fibres, - @required this.sodium, + required this.id, + required this.name, + required this.creationDate, + required this.energy, + required this.carbohydrates, + required this.carbohydratesSugar, + required this.protein, + required this.fat, + required this.fatSaturated, + required this.fibres, + required this.sodium, }); // Boilerplate diff --git a/lib/models/nutrition/ingredient.g.dart b/lib/models/nutrition/ingredient.g.dart index 709079e40..7f3b791e6 100644 --- a/lib/models/nutrition/ingredient.g.dart +++ b/lib/models/nutrition/ingredient.g.dart @@ -23,17 +23,15 @@ Ingredient _$IngredientFromJson(Map json) { return Ingredient( id: json['id'] as int, name: json['name'] as String, - creationDate: json['creation_date'] == null - ? null - : DateTime.parse(json['creation_date'] as String), + creationDate: DateTime.parse(json['creation_date'] as String), energy: json['energy'] as int, - carbohydrates: toNum(json['carbohydrates'] as String), - carbohydratesSugar: toNum(json['carbohydrates_sugar'] as String), - protein: toNum(json['protein'] as String), - fat: toNum(json['fat'] as String), - fatSaturated: toNum(json['fat_saturated'] as String), - fibres: toNum(json['fibres'] as String), - sodium: toNum(json['sodium'] as String), + carbohydrates: toNum(json['carbohydrates'] as String?), + carbohydratesSugar: toNum(json['carbohydrates_sugar'] as String?), + protein: toNum(json['protein'] as String?), + fat: toNum(json['fat'] as String?), + fatSaturated: toNum(json['fat_saturated'] as String?), + fibres: toNum(json['fibres'] as String?), + sodium: toNum(json['sodium'] as String?), ); } diff --git a/lib/models/nutrition/ingredient_weight_unit.dart b/lib/models/nutrition/ingredient_weight_unit.dart index 67d2125aa..951608273 100644 --- a/lib/models/nutrition/ingredient_weight_unit.dart +++ b/lib/models/nutrition/ingredient_weight_unit.dart @@ -16,7 +16,6 @@ * along with this program. If not, see . */ -import 'package:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/weight_unit.dart'; @@ -41,11 +40,11 @@ class IngredientWeightUnit { final double amount; IngredientWeightUnit({ - @required this.id, - @required this.weightUnit, - @required this.ingredient, - @required this.grams, - @required this.amount, + required this.id, + required this.weightUnit, + required this.ingredient, + required this.grams, + required this.amount, }); // Boilerplate diff --git a/lib/models/nutrition/ingredient_weight_unit.g.dart b/lib/models/nutrition/ingredient_weight_unit.g.dart index 152ebcabf..8dc1e54df 100644 --- a/lib/models/nutrition/ingredient_weight_unit.g.dart +++ b/lib/models/nutrition/ingredient_weight_unit.g.dart @@ -16,14 +16,11 @@ IngredientWeightUnit _$IngredientWeightUnitFromJson(Map json) { ]); return IngredientWeightUnit( id: json['id'] as int, - weightUnit: json['weight_unit'] == null - ? null - : WeightUnit.fromJson(json['weight_unit'] as Map), - ingredient: json['ingredient'] == null - ? null - : Ingredient.fromJson(json['ingredient'] as Map), + weightUnit: + WeightUnit.fromJson(json['weight_unit'] as Map), + ingredient: Ingredient.fromJson(json['ingredient'] as Map), grams: json['grams'] as int, - amount: (json['amount'] as num)?.toDouble(), + amount: (json['amount'] as num).toDouble(), ); } diff --git a/lib/models/nutrition/log.dart b/lib/models/nutrition/log.dart index ded992ae6..1f372cc93 100644 --- a/lib/models/nutrition/log.dart +++ b/lib/models/nutrition/log.dart @@ -29,45 +29,48 @@ part 'log.g.dart'; @JsonSerializable() class Log { @JsonKey(required: true) - int id; + int? id; @JsonKey(required: true, name: 'plan') - int planId; + late int planId; @JsonKey(required: true) - DateTime datetime; + late DateTime datetime; - String comment; + String? comment; @JsonKey(required: true, name: 'ingredient') - int ingredientId; + late int ingredientId; - Ingredient ingredientObj; + @JsonKey(ignore: true) + late Ingredient ingredientObj; @JsonKey(required: true, name: 'weight_unit') - int weightUnit; + late int weightUnit; - IngredientWeightUnit weightUnitObj; + IngredientWeightUnit? weightUnitObj; @JsonKey(required: true, fromJson: toNum) - num amount; + late num amount; Log({ this.id, - this.ingredientId, - this.ingredientObj, - this.weightUnit, + required this.ingredientId, + //this.ingredientObj, + required this.weightUnit, this.weightUnitObj, - this.amount, - this.planId, - this.datetime, + required this.amount, + required this.planId, + required this.datetime, this.comment, }); - Log.fromMealItem(MealItem mealItem) { - this.ingredientId = mealItem.ingredientId; + Log.fromMealItem(MealItem mealItem, int planId, [DateTime? dateTime]) { + this.ingredientId = mealItem.ingredientId!; this.ingredientObj = mealItem.ingredientObj; - this.weightUnit = null; + this.weightUnit = mealItem.weightUnit!.id; + this.planId = planId; + this.datetime = dateTime ?? DateTime.now(); this.amount = mealItem.amount; } @@ -80,8 +83,9 @@ class Log { // This is already done on the server. It might be better to read it from there. var out = NutritionalValues(); - final weight = - this.weightUnitObj == null ? amount : amount * weightUnitObj.amount * weightUnitObj.grams; + final weight = amount; + // final weight = + // this.weightUnitObj == null ? amount : amount * weightUnitObj.amount * weightUnitObj.grams; out.energy = ingredientObj.energy * weight / 100; out.protein = ingredientObj.protein * weight / 100; diff --git a/lib/models/nutrition/log.g.dart b/lib/models/nutrition/log.g.dart index 475e4f906..278c4e80c 100644 --- a/lib/models/nutrition/log.g.dart +++ b/lib/models/nutrition/log.g.dart @@ -16,32 +16,26 @@ Log _$LogFromJson(Map json) { 'amount' ]); return Log( - id: json['id'] as int, + id: json['id'] as int?, ingredientId: json['ingredient'] as int, - ingredientObj: json['ingredientObj'] == null - ? null - : Ingredient.fromJson(json['ingredientObj'] as Map), weightUnit: json['weight_unit'] as int, weightUnitObj: json['weightUnitObj'] == null ? null : IngredientWeightUnit.fromJson( json['weightUnitObj'] as Map), - amount: toNum(json['amount'] as String), + amount: toNum(json['amount'] as String?), planId: json['plan'] as int, - datetime: json['datetime'] == null - ? null - : DateTime.parse(json['datetime'] as String), - comment: json['comment'] as String, + datetime: DateTime.parse(json['datetime'] as String), + comment: json['comment'] as String?, ); } Map _$LogToJson(Log instance) => { 'id': instance.id, 'plan': instance.planId, - 'datetime': instance.datetime?.toIso8601String(), + 'datetime': instance.datetime.toIso8601String(), 'comment': instance.comment, 'ingredient': instance.ingredientId, - 'ingredientObj': instance.ingredientObj, 'weight_unit': instance.weightUnit, 'weightUnitObj': instance.weightUnitObj, 'amount': instance.amount, diff --git a/lib/models/nutrition/meal.dart b/lib/models/nutrition/meal.dart index 384fb5270..76e04cdea 100644 --- a/lib/models/nutrition/meal.dart +++ b/lib/models/nutrition/meal.dart @@ -28,23 +28,31 @@ part 'meal.g.dart'; @JsonSerializable() class Meal { @JsonKey(required: false) - final int id; + late int? id; @JsonKey(required: false) - int plan; + late int plan; @JsonKey(required: true, toJson: timeToString, fromJson: stringToTime) - TimeOfDay time; + late TimeOfDay time; @JsonKey(required: false, name: 'meal_items', defaultValue: []) List mealItems = []; Meal({ this.id, - this.plan, - this.time, - this.mealItems, - }); + int? plan, + TimeOfDay? time, + //List? mealItems, + }) { + if (plan != null) { + this.plan = plan; + } + + this.time = time ?? TimeOfDay.now(); + + this.mealItems = []; + } // Boilerplate factory Meal.fromJson(Map json) => _$MealFromJson(json); diff --git a/lib/models/nutrition/meal.g.dart b/lib/models/nutrition/meal.g.dart index 16e9f6566..15fd7d355 100644 --- a/lib/models/nutrition/meal.g.dart +++ b/lib/models/nutrition/meal.g.dart @@ -9,15 +9,13 @@ part of 'meal.dart'; Meal _$MealFromJson(Map json) { $checkKeys(json, requiredKeys: const ['time']); return Meal( - id: json['id'] as int, - plan: json['plan'] as int, - time: stringToTime(json['time'] as String), - mealItems: (json['meal_items'] as List) - ?.map((e) => - e == null ? null : MealItem.fromJson(e as Map)) - ?.toList() ?? - [], - ); + id: json['id'] as int?, + plan: json['plan'] as int?, + time: stringToTime(json['time'] as String?), + )..mealItems = (json['meal_items'] as List?) + ?.map((e) => MealItem.fromJson(e as Map)) + .toList() ?? + []; } Map _$MealToJson(Meal instance) => { diff --git a/lib/models/nutrition/meal_item.dart b/lib/models/nutrition/meal_item.dart index 5dd0323b3..c7ee4dcbf 100644 --- a/lib/models/nutrition/meal_item.dart +++ b/lib/models/nutrition/meal_item.dart @@ -28,29 +28,42 @@ part 'meal_item.g.dart'; @JsonSerializable() class MealItem { @JsonKey(required: true) - final int id; + int? id; @JsonKey(required: false, name: 'ingredient') - int ingredientId; + int? ingredientId; @JsonKey(required: false, name: 'ingredient_obj') - Ingredient ingredientObj; + late Ingredient ingredientObj; @JsonKey(required: false) - int meal; + late int meal; @JsonKey(required: false, name: 'weight_unit') - IngredientWeightUnit weightUnit; + IngredientWeightUnit? weightUnit; @JsonKey(required: true, fromJson: toNum, toJson: toString) - num amount; + late num amount; MealItem({ this.id, - this.ingredientObj, + int? meal, + //this.ingredientObj, + ingredientId, this.weightUnit, - this.amount, - }); + num? amount, + }) { + if (meal != null) { + this.meal = meal; + } + + if (ingredientId != null) { + this.ingredientId = ingredientId; + } + if (amount != null) { + this.amount = amount; + } + } // Boilerplate factory MealItem.fromJson(Map json) => _$MealItemFromJson(json); @@ -62,24 +75,16 @@ class MealItem { // This is already done on the server. It might be better to read it from there. var out = NutritionalValues(); - final weight = this.weightUnit == null ? amount : amount * weightUnit.amount * weightUnit.grams; + //final weight = this.weightUnit == null ? amount : amount * weightUnit.amount * weightUnit.grams; + final weight = amount; out.energy = ingredientObj.energy * weight / 100; out.protein = ingredientObj.protein * weight / 100; out.carbohydrates = ingredientObj.carbohydrates * weight / 100; out.fat = ingredientObj.fat * weight / 100; - - if (ingredientObj.fatSaturated != null) { - out.fatSaturated = ingredientObj.fatSaturated * weight / 100; - } - - if (ingredientObj.fibres != null) { - out.fibres = ingredientObj.fibres * weight / 100; - } - - if (ingredientObj.sodium != null) { - out.sodium = ingredientObj.sodium * weight / 100; - } + out.fatSaturated = ingredientObj.fatSaturated * weight / 100; + out.fibres = ingredientObj.fibres * weight / 100; + out.sodium = ingredientObj.sodium * weight / 100; return out; } diff --git a/lib/models/nutrition/meal_item.g.dart b/lib/models/nutrition/meal_item.g.dart index f821ee9d6..1ca8bd374 100644 --- a/lib/models/nutrition/meal_item.g.dart +++ b/lib/models/nutrition/meal_item.g.dart @@ -9,18 +9,16 @@ part of 'meal_item.dart'; MealItem _$MealItemFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'amount']); return MealItem( - id: json['id'] as int, - ingredientObj: json['ingredient_obj'] == null - ? null - : Ingredient.fromJson(json['ingredient_obj'] as Map), + id: json['id'] as int?, + meal: json['meal'] as int, + ingredientId: json['ingredient'] as int, weightUnit: json['weight_unit'] == null ? null : IngredientWeightUnit.fromJson( json['weight_unit'] as Map), - amount: toNum(json['amount'] as String), - ) - ..ingredientId = json['ingredient'] as int - ..meal = json['meal'] as int; + amount: toNum(json['amount'] as String?), + )..ingredientObj = + Ingredient.fromJson(json['ingredient_obj'] as Map); } Map _$MealItemToJson(MealItem instance) => { diff --git a/lib/models/nutrition/nutritional_plan.dart b/lib/models/nutrition/nutritional_plan.dart index e95f040d1..18e192804 100644 --- a/lib/models/nutrition/nutritional_plan.dart +++ b/lib/models/nutrition/nutritional_plan.dart @@ -28,7 +28,7 @@ part 'nutritional_plan.g.dart'; @JsonSerializable(explicitToJson: true) class NutritionalPlan { @JsonKey(required: true) - int id; + int? id; @JsonKey(required: true) String description; @@ -44,12 +44,15 @@ class NutritionalPlan { NutritionalPlan({ this.id, - this.description, - this.creationDate, - this.meals, - //this.logs, + required this.description, + required this.creationDate, + //List? meals, + //logs, }) { - this.meals = meals ?? []; + //this.meals = meals as List ?? []; + this.meals = []; + //this.logs = logs ?? []; + this.logs = []; } // Boilerplate @@ -78,7 +81,7 @@ class NutritionalPlan { out[date] = NutritionalValues(); } - out[date].add(log.nutritionalValues); + out[date]!.add(log.nutritionalValues); } return out; diff --git a/lib/models/nutrition/nutritional_plan.g.dart b/lib/models/nutrition/nutritional_plan.g.dart index 7027082fb..a1d098bc6 100644 --- a/lib/models/nutrition/nutritional_plan.g.dart +++ b/lib/models/nutrition/nutritional_plan.g.dart @@ -9,17 +9,13 @@ part of 'nutritional_plan.dart'; NutritionalPlan _$NutritionalPlanFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'description', 'creation_date']); return NutritionalPlan( - id: json['id'] as int, + id: json['id'] as int?, description: json['description'] as String, - creationDate: json['creation_date'] == null - ? null - : DateTime.parse(json['creation_date'] as String), - meals: (json['meals'] as List) - ?.map((e) => - e == null ? null : Meal.fromJson(e as Map)) - ?.toList() ?? - [], - ); + creationDate: DateTime.parse(json['creation_date'] as String), + )..meals = (json['meals'] as List?) + ?.map((e) => Meal.fromJson(e as Map)) + .toList() ?? + []; } Map _$NutritionalPlanToJson(NutritionalPlan instance) => @@ -27,5 +23,5 @@ Map _$NutritionalPlanToJson(NutritionalPlan instance) => 'id': instance.id, 'description': instance.description, 'creation_date': toDate(instance.creationDate), - 'meals': instance.meals?.map((e) => e?.toJson())?.toList(), + 'meals': instance.meals.map((e) => e.toJson()).toList(), }; diff --git a/lib/models/nutrition/weight_unit.dart b/lib/models/nutrition/weight_unit.dart index 0565cb5a8..df4bbf0cc 100644 --- a/lib/models/nutrition/weight_unit.dart +++ b/lib/models/nutrition/weight_unit.dart @@ -16,7 +16,6 @@ * along with this program. If not, see . */ -import 'package:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; part 'weight_unit.g.dart'; @@ -30,8 +29,8 @@ class WeightUnit { final String name; WeightUnit({ - @required this.id, - @required this.name, + required this.id, + required this.name, }); // Boilerplate diff --git a/lib/models/workouts/day.dart b/lib/models/workouts/day.dart index 58eb79636..8867842ec 100644 --- a/lib/models/workouts/day.dart +++ b/lib/models/workouts/day.dart @@ -7,10 +7,10 @@ part 'day.g.dart'; @JsonSerializable() class Day { @JsonKey(required: true) - final int id; + int? id; @JsonKey(required: true) - String description; + late String description; @JsonKey(required: false, name: 'day', defaultValue: []) List daysOfWeek = []; @@ -19,19 +19,25 @@ class Day { List sets = []; @JsonKey(required: true, name: 'training') - int workoutId; + late int workoutId; //@JsonKey(required: true, name: 'training') - WorkoutPlan workout; + late WorkoutPlan workout; - Day({ - this.id, - this.workoutId, - this.description, - this.daysOfWeek, - this.sets, + Day() { + this.daysOfWeek = []; + this.sets = []; + } + + Day.withData({ + required this.id, + required this.workoutId, + required this.description, + List? daysOfWeek, + List? sets, }) { this.daysOfWeek = daysOfWeek ?? []; + this.sets = sets ?? []; } static const Map weekdays = { @@ -45,7 +51,7 @@ class Day { }; String getDayName(int weekDay) { - return weekdays[weekDay]; + return weekdays[weekDay]!; } String get getDaysText { diff --git a/lib/models/workouts/day.g.dart b/lib/models/workouts/day.g.dart index 9edbef266..0066e3af7 100644 --- a/lib/models/workouts/day.g.dart +++ b/lib/models/workouts/day.g.dart @@ -8,18 +8,16 @@ part of 'day.dart'; Day _$DayFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'description', 'training']); - return Day( - id: json['id'] as int, - description: json['description'] as String, - daysOfWeek: (json['day'] as List)?.map((e) => e as int)?.toList() ?? [], - sets: (json['sets'] as List) - ?.map((e) => e == null ? null : Set.fromJson(e as Map)) - ?.toList(), - ) + return Day() + ..id = json['id'] as int? + ..description = json['description'] as String + ..daysOfWeek = + (json['day'] as List?)?.map((e) => e as int).toList() ?? [] + ..sets = (json['sets'] as List) + .map((e) => Set.fromJson(e as Map)) + .toList() ..workoutId = json['training'] as int - ..workout = json['workout'] == null - ? null - : WorkoutPlan.fromJson(json['workout'] as Map); + ..workout = WorkoutPlan.fromJson(json['workout'] as Map); } Map _$DayToJson(Day instance) => { diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index 08f558b2f..cff68aff3 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -6,45 +6,47 @@ part 'log.g.dart'; @JsonSerializable() class Log { @JsonKey(required: true) - final int id; + int? id; @JsonKey(required: true) - int exercise; + late int exercise; @JsonKey(required: true, name: 'workout') - int workoutPlan; + late int workoutPlan; @JsonKey(required: true) - int reps; + late int reps; @JsonKey(required: false) - double rir; + late String rir; @JsonKey(required: true, name: 'repetition_unit') - int repetitionUnit; + late int repetitionUnit; @JsonKey(required: true, fromJson: toNum, toJson: toString) - num weight; + late num weight; @JsonKey(required: true, name: 'weight_unit') - int weightUnit; + late int weightUnit; @JsonKey(required: true, toJson: toDate) - DateTime date; + late DateTime date; //@JsonKey(required: true) //String comment; - Log({ + Log(); + + Log.withData({ this.id, - this.exercise, - this.workoutPlan, - this.repetitionUnit, - this.reps, - this.rir, - this.weight, - this.weightUnit, - this.date, + required this.exercise, + required this.workoutPlan, + required this.repetitionUnit, + required this.reps, + required this.rir, + required this.weight, + required this.weightUnit, + required this.date, }); // Boilerplate diff --git a/lib/models/workouts/log.g.dart b/lib/models/workouts/log.g.dart index 2e40d9111..be478d010 100644 --- a/lib/models/workouts/log.g.dart +++ b/lib/models/workouts/log.g.dart @@ -17,17 +17,16 @@ Log _$LogFromJson(Map json) { 'weight_unit', 'date' ]); - return Log( - id: json['id'] as int, - exercise: json['exercise'] as int, - workoutPlan: json['workout'] as int, - repetitionUnit: json['repetition_unit'] as int, - reps: json['reps'] as int, - rir: (json['rir'] as num)?.toDouble(), - weight: toNum(json['weight'] as String), - weightUnit: json['weight_unit'] as int, - date: json['date'] == null ? null : DateTime.parse(json['date'] as String), - ); + return Log() + ..id = json['id'] as int? + ..exercise = json['exercise'] as int + ..workoutPlan = json['workout'] as int + ..reps = json['reps'] as int + ..rir = json['rir'] as String + ..repetitionUnit = json['repetition_unit'] as int + ..weight = toNum(json['weight'] as String?) + ..weightUnit = json['weight_unit'] as int + ..date = DateTime.parse(json['date'] as String); } Map _$LogToJson(Log instance) => { diff --git a/lib/models/workouts/repetition_unit.dart b/lib/models/workouts/repetition_unit.dart index a2611bb51..a43bf7d43 100644 --- a/lib/models/workouts/repetition_unit.dart +++ b/lib/models/workouts/repetition_unit.dart @@ -1,4 +1,3 @@ -import 'package:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; part 'repetition_unit.g.dart'; @@ -12,8 +11,8 @@ class RepetitionUnit { final String name; RepetitionUnit({ - @required this.id, - @required this.name, + required this.id, + required this.name, }); // Boilerplate diff --git a/lib/models/workouts/session.dart b/lib/models/workouts/session.dart index d7380282d..65b9108af 100644 --- a/lib/models/workouts/session.dart +++ b/lib/models/workouts/session.dart @@ -9,34 +9,36 @@ const ImpressionMap = {1: 'bad', 2: 'neutral', 3: 'good'}; @JsonSerializable() class WorkoutSession { @JsonKey(required: true) - int id; + int? id; @JsonKey(required: true, name: 'workout') - int workoutId; + late int workoutId; @JsonKey(required: true, toJson: toDate) - DateTime date; + late DateTime date; @JsonKey(required: true, fromJson: toNum, toJson: toString) - num impression; + late num impression; @JsonKey(required: false, defaultValue: '') - String notes; + late String notes; @JsonKey(required: true, name: 'time_start', toJson: timeToString, fromJson: stringToTime) - TimeOfDay timeStart; + late TimeOfDay timeStart; @JsonKey(required: true, name: 'time_end', toJson: timeToString, fromJson: stringToTime) - TimeOfDay timeEnd; + late TimeOfDay timeEnd; - WorkoutSession({ - this.id, - this.workoutId, - this.date, - this.impression, - this.notes, - this.timeStart, - this.timeEnd, + WorkoutSession(); + + WorkoutSession.withData({ + required this.id, + required this.workoutId, + required this.date, + required this.impression, + required this.notes, + required this.timeStart, + required this.timeEnd, }); // Boilerplate diff --git a/lib/models/workouts/session.g.dart b/lib/models/workouts/session.g.dart index 6ac969657..7345d9524 100644 --- a/lib/models/workouts/session.g.dart +++ b/lib/models/workouts/session.g.dart @@ -15,15 +15,14 @@ WorkoutSession _$WorkoutSessionFromJson(Map json) { 'time_start', 'time_end' ]); - return WorkoutSession( - id: json['id'] as int, - workoutId: json['workout'] as int, - date: json['date'] == null ? null : DateTime.parse(json['date'] as String), - impression: toNum(json['impression'] as String), - notes: json['notes'] as String ?? '', - timeStart: stringToTime(json['time_start'] as String), - timeEnd: stringToTime(json['time_end'] as String), - ); + return WorkoutSession() + ..id = json['id'] as int? + ..workoutId = json['workout'] as int + ..date = DateTime.parse(json['date'] as String) + ..impression = toNum(json['impression'] as String?) + ..notes = json['notes'] as String? ?? '' + ..timeStart = stringToTime(json['time_start'] as String?) + ..timeEnd = stringToTime(json['time_end'] as String?); } Map _$WorkoutSessionToJson(WorkoutSession instance) => diff --git a/lib/models/workouts/set.dart b/lib/models/workouts/set.dart index 113654c38..17cb55ea8 100644 --- a/lib/models/workouts/set.dart +++ b/lib/models/workouts/set.dart @@ -9,16 +9,16 @@ class Set { static const DEFAULT_NR_SETS = 4; @JsonKey(required: true) - int id; + int? id; @JsonKey(required: true) - int sets; + late int sets; @JsonKey(required: false, name: 'exerciseday') - int day; + late int day; @JsonKey(required: true) - int order; + late int order; //@JsonKey(required: true) List exercisesObj = []; @@ -33,20 +33,32 @@ class Set { @JsonKey(required: false) List settingsComputed = []; - Set({ + Set() { + this.sets = sets; + this.exercisesObj = []; + this.exercisesIds = exercisesObj.map((e) => e.id).toList(); + this.settings; + this.settingsComputed; + } + + Set.withData({ this.id, sets, - this.day, - this.order, + day, + order, exercises, settings, settingsComputed, }) { this.sets = sets ?? DEFAULT_NR_SETS; + this.order = order ?? 1; this.exercisesObj = exercises ?? []; this.exercisesIds = exercisesObj.map((e) => e.id).toList(); this.settings = settings ?? []; this.settingsComputed = settingsComputed ?? []; + if (day != null) { + this.day = day; + } } void addExercise(Exercise exercise) { diff --git a/lib/models/workouts/set.g.dart b/lib/models/workouts/set.g.dart index 2d908d65c..b063cb608 100644 --- a/lib/models/workouts/set.g.dart +++ b/lib/models/workouts/set.g.dart @@ -8,20 +8,22 @@ part of 'set.dart'; Set _$SetFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'sets', 'order']); - return Set( - id: json['id'] as int, - sets: json['sets'], - day: json['exerciseday'] as int, - order: json['order'] as int, - settings: json['settings'], - settingsComputed: json['settingsComputed'], - ) - ..exercisesObj = (json['exercisesObj'] as List) - ?.map((e) => - e == null ? null : Exercise.fromJson(e as Map)) - ?.toList() + return Set() + ..id = json['id'] as int? + ..sets = json['sets'] as int + ..day = json['exerciseday'] as int + ..order = json['order'] as int + ..exercisesObj = (json['exercisesObj'] as List) + .map((e) => Exercise.fromJson(e as Map)) + .toList() ..exercisesIds = - (json['exercises'] as List)?.map((e) => e as int)?.toList(); + (json['exercises'] as List).map((e) => e as int).toList() + ..settings = (json['settings'] as List) + .map((e) => Setting.fromJson(e as Map)) + .toList() + ..settingsComputed = (json['settingsComputed'] as List) + .map((e) => Setting.fromJson(e as Map)) + .toList(); } Map _$SetToJson(Set instance) => { diff --git a/lib/models/workouts/setting.dart b/lib/models/workouts/setting.dart index 77fbba377..7dbf9a521 100644 --- a/lib/models/workouts/setting.dart +++ b/lib/models/workouts/setting.dart @@ -7,53 +7,62 @@ part 'setting.g.dart'; @JsonSerializable() class Setting { @JsonKey(required: true) - int id; + int? id; @JsonKey(required: true, name: 'set') - int setId; + late int setId; - @JsonKey(required: false) - Exercise exerciseObj; + @JsonKey(ignore: true) + late Exercise exerciseObj; @JsonKey(required: true, name: 'exercise') - int exerciseId; + late int exerciseId; @JsonKey(required: true, name: 'repetition_unit') - int repetitionUnit; + late int repetitionUnitId; + + @JsonKey(ignore: true) + late int repetitionUnitObj; @JsonKey(required: true) - int reps; + late int reps; @JsonKey(required: true, fromJson: toNum, toJson: toString) - num weight; + late num weight; @JsonKey(required: true, name: 'weight_unit') - int weightUnit; + late int weightUnitId; + + @JsonKey(ignore: true) + late int weightUnitObj; @JsonKey(required: true, defaultValue: '') - String comment = ''; + late String comment = ''; @JsonKey(required: false, defaultValue: '') - String rir = ''; + late String rir = ''; // Generated by Server @JsonKey(required: false) - String repsText; + late String repsText; - Setting({ + Setting(); + + Setting.withData({ this.id, - this.setId, - this.exerciseObj, - this.repetitionUnit, - this.reps, - this.weight, - this.weightUnit, - this.comment, - this.rir, - this.repsText, + required this.setId, + Exercise? exerciseObj, + required this.repetitionUnitId, + required this.reps, + required this.weight, + required this.weightUnitId, + required this.comment, + this.rir = '', + required this.repsText, }) { if (exerciseObj != null) { this.exerciseId = exerciseObj.id; + this.exerciseObj = exerciseObj; } } diff --git a/lib/models/workouts/setting.g.dart b/lib/models/workouts/setting.g.dart index 369e7fd47..e80e60825 100644 --- a/lib/models/workouts/setting.g.dart +++ b/lib/models/workouts/setting.g.dart @@ -17,31 +17,27 @@ Setting _$SettingFromJson(Map json) { 'weight_unit', 'comment' ]); - return Setting( - id: json['id'] as int, - setId: json['set'] as int, - exerciseObj: json['exerciseObj'] == null - ? null - : Exercise.fromJson(json['exerciseObj'] as Map), - repetitionUnit: json['repetition_unit'] as int, - reps: json['reps'] as int, - weight: toNum(json['weight'] as String), - weightUnit: json['weight_unit'] as int, - comment: json['comment'] as String ?? '', - rir: json['rir'] as String ?? '', - repsText: json['repsText'] as String, - )..exerciseId = json['exercise'] as int; + return Setting() + ..id = json['id'] as int? + ..setId = json['set'] as int + ..exerciseId = json['exercise'] as int + ..repetitionUnitId = json['repetition_unit'] as int + ..reps = json['reps'] as int + ..weight = toNum(json['weight'] as String?) + ..weightUnitId = json['weight_unit'] as int + ..comment = json['comment'] as String? ?? '' + ..rir = json['rir'] as String? ?? '' + ..repsText = json['repsText'] as String; } Map _$SettingToJson(Setting instance) => { 'id': instance.id, 'set': instance.setId, - 'exerciseObj': instance.exerciseObj, 'exercise': instance.exerciseId, - 'repetition_unit': instance.repetitionUnit, + 'repetition_unit': instance.repetitionUnitId, 'reps': instance.reps, 'weight': toString(instance.weight), - 'weight_unit': instance.weightUnit, + 'weight_unit': instance.weightUnitId, 'comment': instance.comment, 'rir': instance.rir, 'repsText': instance.repsText, diff --git a/lib/models/workouts/weight_unit.dart b/lib/models/workouts/weight_unit.dart index 608d2d12d..88aa74fbd 100644 --- a/lib/models/workouts/weight_unit.dart +++ b/lib/models/workouts/weight_unit.dart @@ -11,8 +11,8 @@ class WeightUnit { final String name; WeightUnit({ - this.id, - this.name, + required this.id, + required this.name, }); // Boilerplate diff --git a/lib/models/workouts/workout_plan.dart b/lib/models/workouts/workout_plan.dart index 6807a516a..7251911de 100644 --- a/lib/models/workouts/workout_plan.dart +++ b/lib/models/workouts/workout_plan.dart @@ -26,27 +26,31 @@ part 'workout_plan.g.dart'; @JsonSerializable() class WorkoutPlan { @JsonKey(required: true) - final int id; + int? id; @JsonKey(required: true, name: 'creation_date') - DateTime creationDate; + late DateTime creationDate; @JsonKey(required: true, name: 'comment') - String description; + late String description; @JsonKey(required: false, defaultValue: [], name: 'days') - List days = []; + late List days = []; @JsonKey(ignore: true, defaultValue: []) - List logs = []; + late List logs = []; - WorkoutPlan({ + WorkoutPlan(); + + WorkoutPlan.withData({ this.id, - this.creationDate, - this.description, - this.days, + required this.creationDate, + required this.description, + days, + logs, }) { this.days = days ?? []; + this.logs = logs ?? []; } // Boilerplate diff --git a/lib/models/workouts/workout_plan.g.dart b/lib/models/workouts/workout_plan.g.dart index f443b0af3..04c54f818 100644 --- a/lib/models/workouts/workout_plan.g.dart +++ b/lib/models/workouts/workout_plan.g.dart @@ -8,24 +8,20 @@ part of 'workout_plan.dart'; WorkoutPlan _$WorkoutPlanFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'creation_date', 'comment']); - return WorkoutPlan( - id: json['id'] as int, - creationDate: json['creation_date'] == null - ? null - : DateTime.parse(json['creation_date'] as String), - description: json['comment'] as String, - days: (json['days'] as List) - ?.map((e) => - e == null ? null : Day.fromJson(e as Map)) - ?.toList() ?? - [], - ); + return WorkoutPlan() + ..id = json['id'] as int? + ..creationDate = DateTime.parse(json['creation_date'] as String) + ..description = json['comment'] as String + ..days = (json['days'] as List?) + ?.map((e) => Day.fromJson(e as Map)) + .toList() ?? + []; } Map _$WorkoutPlanToJson(WorkoutPlan instance) => { 'id': instance.id, - 'creation_date': instance.creationDate?.toIso8601String(), + 'creation_date': instance.creationDate.toIso8601String(), 'comment': instance.description, 'days': instance.days, }; diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index aca622a55..4891742f6 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -34,10 +34,10 @@ import 'package:wger/models/http_exception.dart'; import 'helpers.dart'; class Auth with ChangeNotifier { - String token; - String serverUrl; - String serverVersion; - PackageInfo applicationVersion; + String? token; + String? serverUrl; + String? serverVersion; + PackageInfo? applicationVersion; /// flag to indicate that the application has successfully loaded all initial data bool dataInit = false; @@ -50,7 +50,7 @@ class Auth with ChangeNotifier { return token != null; } - String get token2 { + String? get token2 { // if (_expiryDate != null && // _expiryDate.isAfter(DateTime.now()) && // _token != null) { @@ -65,7 +65,7 @@ class Auth with ChangeNotifier { /// Server application version Future setServerVersion() async { - final response = await http.get(makeUri(serverUrl, 'version')); + final response = await http.get(makeUri(serverUrl!, 'version')); final responseData = json.decode(response.body); serverVersion = responseData; } @@ -77,7 +77,12 @@ class Auth with ChangeNotifier { } /// Registers a new user - Future register({String username, String password, String email, String serverUrl}) async { + Future register({ + required String username, + required String password, + required String email, + required String serverUrl, + }) async { final uri = Uri.parse(serverUrl + '/api/v2/register/'); Map metadata = Map(); @@ -134,7 +139,7 @@ class Auth with ChangeNotifier { } // Log user in - this.serverUrl = serverUrl ?? ''; + this.serverUrl = serverUrl; token = responseData['token']; // _userId = responseData['localId']; @@ -173,8 +178,8 @@ class Auth with ChangeNotifier { return DEFAULT_SERVER; } - final userData = json.decode(prefs.getString('lastServer')) as Map; - return userData['serverUrl']; + final userData = json.decode(prefs.getString('lastServer')!); + return userData['serverUrl'] as String; } Future tryAutoLogin() async { @@ -183,16 +188,15 @@ class Auth with ChangeNotifier { log('autologin failed'); return false; } - - final extractedUserData = json.decode(prefs.getString('userData')) as Map; + final extractedUserData = json.decode(prefs.getString('userData')!); // final expiryDate = DateTime.parse(extractedUserData['expiryDate']); // if (expiryDate.isBefore(DateTime.now())) { // return false; // } - token = extractedUserData['token']; - serverUrl = extractedUserData['serverUrl']; + token = extractedUserData['token']!; + serverUrl = extractedUserData['serverUrl']!; // _userId = extractedUserData['userId']; // _expiryDate = expiryDate; diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index e6f9c03e6..8a9e206d5 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -30,20 +30,20 @@ import 'package:wger/providers/helpers.dart'; /// Provides a couple of comfort functions so we avoid a bit of boilerplate. class WgerBaseProvider { Auth auth; - http.Client client; + late http.Client client; - WgerBaseProvider(auth, [client]) { + WgerBaseProvider(this.auth, [http.Client? client]) { this.auth = auth; this.client = client ?? http.Client(); } /// Helper function to make a URL. - makeUrl(String path, {int id, String objectMethod, Map query}) { - return makeUri(auth.serverUrl, path, id, objectMethod, query); + makeUrl(String path, {int? id, String? objectMethod, Map? query}) { + return makeUri(auth.serverUrl!, path, id, objectMethod, query); } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response - Future> fetch([Uri uri]) async { + Future> fetch(Uri uri) async { // Send the request final response = await client.get( uri, diff --git a/lib/providers/body_weight.dart b/lib/providers/body_weight.dart index 5cb115ef0..285a6b624 100644 --- a/lib/providers/body_weight.dart +++ b/lib/providers/body_weight.dart @@ -27,7 +27,7 @@ class BodyWeight extends WgerBaseProvider with ChangeNotifier { static const bodyWeightUrl = 'weightentry'; List _entries = []; - BodyWeight(Auth auth, List entries, [http.Client client]) + BodyWeight(Auth auth, List entries, [http.Client? client]) : this._entries = entries, super(auth, client); @@ -86,6 +86,5 @@ class BodyWeight extends WgerBaseProvider with ChangeNotifier { notifyListeners(); throw WgerHttpException(response.body); } - existingWeightEntry = null; } } diff --git a/lib/providers/exercises.dart b/lib/providers/exercises.dart index d4ebd3088..372a52f98 100644 --- a/lib/providers/exercises.dart +++ b/lib/providers/exercises.dart @@ -48,7 +48,7 @@ class Exercises extends WgerBaseProvider with ChangeNotifier { List _muscles = []; List _equipment = []; - Exercises(Auth auth, List entries, [http.Client client]) + Exercises(Auth auth, List entries, [http.Client? client]) : this._exercises = entries, super(auth, client); @@ -57,10 +57,7 @@ class Exercises extends WgerBaseProvider with ChangeNotifier { } Exercise findById(int id) { - return _exercises.firstWhere((exercise) => exercise.id == id, orElse: () { - log('Could not find exercise with ID $id'); - return null; - }); + return _exercises.firstWhere((exercise) => exercise.id == id); } Future fetchAndSetCategories() async { @@ -103,7 +100,7 @@ class Exercises extends WgerBaseProvider with ChangeNotifier { // Load exercises from cache, if available final prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('exerciseData')) { - final exerciseData = json.decode(prefs.getString('exerciseData')); + final exerciseData = json.decode(prefs.getString('exerciseData')!); if (DateTime.parse(exerciseData['expiresIn']).isAfter(DateTime.now())) { exerciseData['exercises'].forEach((e) => _exercises.add(Exercise.fromJson(e))); exerciseData['equipment'].forEach((e) => _equipment.add(Equipment.fromJson(e))); diff --git a/lib/providers/helpers.dart b/lib/providers/helpers.dart index 362da4f8c..4ddf5d401 100644 --- a/lib/providers/helpers.dart +++ b/lib/providers/helpers.dart @@ -17,7 +17,13 @@ */ /// Helper function to make a URL. -makeUri(String serverUrl, String path, [int id, String objectMethod, Map query]) { +makeUri( + String serverUrl, + String path, [ + int? id, + String? objectMethod, + Map? query, +]) { Uri uriServer = Uri.parse(serverUrl); var pathList = ['api', 'v2', path]; diff --git a/lib/providers/nutrition.dart b/lib/providers/nutrition.dart index db06e55f5..79c7eede1 100644 --- a/lib/providers/nutrition.dart +++ b/lib/providers/nutrition.dart @@ -46,7 +46,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { List _plans = []; List _ingredients = []; - Nutrition(Auth auth, List entries, [http.Client client]) + Nutrition(Auth auth, List entries, [http.Client? client]) : this._plans = entries, super(auth, client); @@ -56,7 +56,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { /// Returns the current active nutritional plan. At the moment this is just /// the latest, but this might change in the future. - NutritionalPlan get currentPlan { + NutritionalPlan? get currentPlan { if (_plans.length > 0) { return _plans.first; } @@ -66,9 +66,9 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { return _plans.firstWhere((plan) => plan.id == id); } - Meal findMealById(int id) { + Meal? findMealById(int id) { for (var plan in _plans) { - var meal = plan.meals.firstWhere((plan) => plan.id == id, orElse: () {}); + var meal = plan.meals.firstWhere((plan) => plan.id == id); if (meal != null) { return meal; } @@ -81,7 +81,13 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { await fetch(makeUrl(_nutritionalPlansInfoPath, query: {'ordering': '-creation_date'})); final List loadedPlans = []; for (final entry in data['results']) { - loadedPlans.add(NutritionalPlan.fromJson(entry)); + try { + //log(entry.toString()); + loadedPlans.add(NutritionalPlan.fromJson(entry)); + } catch (e) { + log(e.toString()); + //log(); + } } _plans = loadedPlans; @@ -124,7 +130,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { notifyListeners(); throw WgerHttpException(response.body); } - existingPlan = null; + //existingPlan = null; } /// Adds a meal to a plan @@ -158,22 +164,21 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { notifyListeners(); // Try to delete - final response = await deleteRequest(_mealPath, meal.id); + final response = await deleteRequest(_mealPath, meal.id!); if (response.statusCode >= 400) { plan.meals.insert(mealIndex, existingMeal); notifyListeners(); throw WgerHttpException(response.body); } - existingMeal = null; } /// Adds a meal item to a meal Future addMealItem(MealItem mealItem, int mealId) async { - var meal = findMealById(mealId); + var meal = findMealById(mealId)!; final data = await post(mealItem.toJson(), makeUrl(_mealItemPath)); mealItem = MealItem.fromJson(data); - mealItem.ingredientObj = await fetchIngredient(mealItem.ingredientId); + mealItem.ingredientObj = await fetchIngredient(mealItem.ingredientId!); meal.mealItems.add(mealItem); notifyListeners(); @@ -183,27 +188,26 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { /// Deletes a meal Future deleteMealItem(MealItem mealItem) async { // Get the meal - var meal = findMealById(mealItem.meal); + var meal = findMealById(mealItem.meal)!; final mealItemIndex = meal.mealItems.indexWhere((e) => e.id == mealItem.id); var existingMealItem = meal.mealItems[mealItemIndex]; meal.mealItems.removeAt(mealItemIndex); notifyListeners(); // Try to delete - final response = await deleteRequest(_mealItemPath, mealItem.id); + final response = await deleteRequest(_mealItemPath, mealItem.id!); if (response.statusCode >= 400) { meal.mealItems.insert(mealItemIndex, existingMealItem); notifyListeners(); throw WgerHttpException(response.body); } - existingMealItem = null; } /// Fetch and return an ingredient /// /// If the ingredient is not known locally, it is fetched from the server Future fetchIngredient(int ingredientId) async { - var ingredient = _ingredients.firstWhere((e) => e.id == ingredientId, orElse: () => null); + var ingredient = _ingredients.firstWhere((e) => e.id == ingredientId); if (ingredient != null) { return ingredient; } @@ -214,7 +218,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { _ingredients.add(ingredient); final prefs = await SharedPreferences.getInstance(); - final ingredientData = json.decode(prefs.getString('ingredientData')); + final ingredientData = json.decode(prefs.getString('ingredientData')!); ingredientData['ingredients'].add(ingredient.toJson()); prefs.setString('ingredientData', json.encode(ingredientData)); log("Saved ingredient '${ingredient.name}' to cache."); @@ -227,7 +231,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { // Load exercises from cache, if available final prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('ingredientData')) { - final ingredientData = json.decode(prefs.getString('ingredientData')); + final ingredientData = json.decode(prefs.getString('ingredientData')!); if (DateTime.parse(ingredientData['expiresIn']).isAfter(DateTime.now())) { ingredientData['ingredients'].forEach((e) => _ingredients.add(Ingredient.fromJson(e))); log("Read ${ingredientData['ingredients'].length} ingredients from cache. Valid till ${ingredientData['expiresIn']}"); @@ -247,6 +251,10 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { /// Searches for an ingredient Future searchIngredient(String name) async { + if (name.length <= 1) { + return []; + } + // Send the request final response = await client.get( makeUrl(_ingredientSearchPath, query: {'term': name}), @@ -269,10 +277,10 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { Future logMealToDiary(Meal meal) async { //var meal = findMealById(mealId); for (var item in meal.mealItems) { - Log log = Log.fromMealItem(item); final plan = findById(meal.plan); - log.planId = plan.id; - log.datetime = DateTime.now(); + Log log = Log.fromMealItem(item, plan.id!); + //log.planId = plan.id; + //log.datetime = DateTime.now(); final data = await post(log.toJson(), makeUrl(_nutritionDiaryPath)); log.id = data['id']; diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index 5414528ff..255300c8c 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -22,6 +22,7 @@ import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/exercises/image.dart'; import 'package:wger/models/http_exception.dart'; @@ -48,12 +49,12 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { static const _weightUnitUrlPath = 'setting-weightunit'; static const _repetitionUnitUrlPath = 'setting-repetitionunit'; - WorkoutPlan _currentPlan; + WorkoutPlan? _currentPlan; List _workoutPlans = []; List _weightUnits = []; List _repetitionUnit = []; - WorkoutPlans(Auth auth, List entries, [http.Client client]) + WorkoutPlans(Auth auth, List entries, [http.Client? client]) : this._workoutPlans = entries, super(auth, client); @@ -67,7 +68,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { /// Return the default weight unit (kg) WeightUnit get defaultWeightUnit { - return _weightUnits.firstWhere((element) => element.id == 1); + return _weightUnits.firstWhere((element) => element.id == DEFAULT_WEIGHT_UNIT); } List get repetitionUnits { @@ -76,7 +77,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { /// Return the default weight unit (reps) RepetitionUnit get defaultRepetitionUnit { - return _repetitionUnit.firstWhere((element) => element.id == 1); + return _repetitionUnit.firstWhere((element) => element.id == DEFAULT_REPETITION_UNIT); } WorkoutPlan findById(int id) { @@ -93,7 +94,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { } /// Returns the currently "active" workout plan - WorkoutPlan get currentPlan { + WorkoutPlan? get currentPlan { return _currentPlan; } @@ -104,7 +105,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { /// Returns the current active workout plan. At the moment this is just /// the latest, but this might change in the future. - WorkoutPlan get activePlan { + WorkoutPlan? get activePlan { if (_workoutPlans.length > 0) { return _workoutPlans.first; } @@ -127,7 +128,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { Future setAllFullWorkouts() async { for (var plan in _workoutPlans) { - setFullWorkout(plan.id); + setFullWorkout(plan.id!); } } @@ -138,97 +139,102 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { objectMethod: 'canonical_representation', )); - try { - WorkoutPlan workout = _workoutPlans.firstWhere((element) => element.id == workoutId); + //try { + WorkoutPlan workout = _workoutPlans.firstWhere((element) => element.id == workoutId); - List days = []; - for (final entry in data['day_list']) { - List sets = []; - List settingsComputed = []; + List days = []; + for (final entry in data['day_list']) { + List sets = []; + List settingsComputed = []; - for (final set in entry['set_list']) { - List settings = []; - List exercises = []; + for (final set in entry['set_list']) { + List settings = []; + List exercises = []; - for (final exerciseData in set['exercise_list']) { - List images = []; + for (final exerciseData in set['exercise_list']) { + List images = []; - for (final image in exerciseData['image_list']) { - images.add( - ExerciseImage( - url: auth.serverUrl + image["image"], - isMain: image['is_main'], - ), - ); - } - - Exercise exercise = Exercise( - id: exerciseData['obj']['id'], - uuid: exerciseData['obj']['uuid'], - creationDate: DateTime.parse(exerciseData['obj']['creation_date']), - name: exerciseData['obj']['name'], - description: exerciseData['obj']['description'], - images: images, + for (final image in exerciseData['image_list']) { + images.add( + ExerciseImage( + url: auth.serverUrl! + image["image"], + isMain: image['is_main'], + ), ); - exercises.add(exercise); - - // Settings - if (exerciseData['setting_obj_list'].length > 0) { - settings.add( - Setting( - id: exerciseData['setting_obj_list'][0]['id'], - setId: exerciseData['setting_obj_list'][0]['set'], - comment: exerciseData['setting_obj_list'][0]['comment'], - reps: exerciseData['setting_obj_list'][0]['reps'], - //weight: setting['setting_obj_list'][0]['weight'] == null - // ? '' - // : setting['setting_obj_list'][0]['weight'], - repsText: exerciseData['setting_text'], - exerciseObj: exercise, - ), - ); - } } - // Computed settings - for (var setting in set['settings_computed']) { - settingsComputed.add(Setting.fromJson(setting)); - } + //TODO: read exercise data from cache from Exercises provider + Exercise exercise = Exercise( + id: exerciseData['obj']['id'], + uuid: exerciseData['obj']['uuid'], + creationDate: DateTime.parse(exerciseData['obj']['creation_date']), + name: exerciseData['obj']['name'], + description: exerciseData['obj']['description'], + categoryId: exerciseData['obj']['category'], + images: images, + ); + exercises.add(exercise); - // Sets - sets.add(Set( - id: set['obj']['id'], - sets: set['obj']['sets'], - order: set['obj']['order'], - settings: settings, - settingsComputed: settingsComputed, - exercises: exercises, - )); + // Settings + if (exerciseData['setting_obj_list'].length > 0) { + settings.add( + Setting.withData( + id: exerciseData['setting_obj_list'][0]['id'], + setId: exerciseData['setting_obj_list'][0]['set'], + comment: exerciseData['setting_obj_list'][0]['comment'], + reps: exerciseData['setting_obj_list'][0]['reps'], + weight: 10, + repetitionUnitId: DEFAULT_REPETITION_UNIT, + weightUnitId: DEFAULT_WEIGHT_UNIT, + //weight: setting['setting_obj_list'][0]['weight'] == null + // ? '' + // : setting['setting_obj_list'][0]['weight'], + repsText: exerciseData['setting_text'], + exerciseObj: exercise, + ), + ); + } } - // Days - days.add(Day( - id: entry['obj']['id'], - workoutId: workoutId, - description: entry['obj']['description'], - sets: sets, - daysOfWeek: [1, 3] - //daysOfWeek: entry['obj']['day'], - )); - } - workout.days = days; + // Computed settings + for (var setting in set['settings_computed']) { + settingsComputed.add(Setting.fromJson(setting)); + } - // Logs - final logData = await fetch(makeUrl(_logsUrlPath, query: {'workout': workoutId.toString()})); - for (final entry in logData['results']) { - workout.logs.add(Log.fromJson(entry)); + // Sets + sets.add(Set.withData( + id: set['obj']['id'], + sets: set['obj']['sets'], + order: set['obj']['order'], + settings: settings, + settingsComputed: settingsComputed, + exercises: exercises, + )); } - notifyListeners(); - return workout; - } catch (error) { - throw (error); + // Days + days.add(Day.withData( + id: entry['obj']['id'], + workoutId: workoutId, + description: entry['obj']['description'], + sets: sets, + daysOfWeek: [1, 3] + //daysOfWeek: entry['obj']['day'], + )); } + workout.days = days; + + // Logs + final logData = await fetch(makeUrl(_logsUrlPath, query: {'workout': workoutId.toString()})); + for (final entry in logData['results']) { + workout.logs.add(Log.fromJson(entry)); + } + notifyListeners(); + + return workout; + //} catch (error) { + // throw (error); + //} } Future postWorkout(WorkoutPlan workout) async { @@ -242,7 +248,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { Future patchWorkout(WorkoutPlan workout) async { final data = await patch(workout.toJson(), makeUrl(_workoutPlansUrlPath, id: workout.id)); final plan = WorkoutPlan.fromJson(data); - _workoutPlans[findIndexById(plan.id)] = plan; + _workoutPlans[findIndexById(plan.id!)] = plan; notifyListeners(); return plan; } @@ -260,10 +266,9 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { notifyListeners(); throw WgerHttpException(response.body); } - existingWorkout = null; } - Future fetchLogData(WorkoutPlan workout, Exercise exercise) async { + Future> fetchLogData(WorkoutPlan workout, Exercise exercise) async { final data = await fetch( makeUrl( _workoutPlansUrlPath, @@ -305,7 +310,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { // Load units from cache, if available final prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('workoutUnits')) { - final workoutData = json.decode(prefs.getString('workoutUnits')); + final workoutData = json.decode(prefs.getString('workoutUnits')!); if (DateTime.parse(workoutData['expiresIn']).isAfter(DateTime.now())) { workoutData['repetitionUnits'].forEach( (e) => _repetitionUnit.add(RepetitionUnit.fromJson(e)), @@ -340,7 +345,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { /* * Saves a new day instance to the DB and adds it to the given workout */ - day.workoutId = workout.id; + day.workoutId = workout.id!; final data = await post(day.toJson(), makeUrl(_daysUrlPath)); day = Day.fromJson(data); day.sets = []; @@ -350,7 +355,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { } Future deleteDay(Day day) async { - await deleteRequest(_daysUrlPath, day.id); + await deleteRequest(_daysUrlPath, day.id!); for (var workout in _workoutPlans) { workout.days.removeWhere((element) => element.id == day.id); } @@ -368,7 +373,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { } Future deleteSet(Set workoutSet) async { - await deleteRequest(_setsUrlPath, workoutSet.id); + await deleteRequest(_setsUrlPath, workoutSet.id!); for (var workout in _workoutPlans) { for (var day in workout.days) { diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index 9f2bebae3..7ab6e746d 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -84,9 +84,7 @@ class AuthScreen extends StatelessWidget { } class AuthCard extends StatefulWidget { - const AuthCard({ - Key key, - }) : super(key: key); + const AuthCard(); @override _AuthCardState createState() => _AuthCardState(); @@ -119,11 +117,11 @@ class _AuthCardState extends State { } void _submit(BuildContext context) async { - if (!_formKey.currentState.validate()) { + if (!_formKey.currentState!.validate()) { // Invalid! return; } - _formKey.currentState.save(); + _formKey.currentState!.save(); setState(() { _isLoading = true; }); @@ -131,18 +129,18 @@ class _AuthCardState extends State { // Login existing user if (_authMode == AuthMode.Login) { await Provider.of(context, listen: false).login( - _authData['username'], - _authData['password'], - _authData['serverUrl'], + _authData['username']!, + _authData['password']!, + _authData['serverUrl']!, ); // Register new user } else { await Provider.of(context, listen: false).register( - username: _authData['username'], - password: _authData['password'], - email: _authData['email'], - serverUrl: _authData['serverUrl'], + username: _authData['username']!, + password: _authData['password']!, + email: _authData['email']!, + serverUrl: _authData['serverUrl']!, ); } @@ -190,25 +188,25 @@ class _AuthCardState extends State { children: [ TextFormField( key: Key('inputUsername'), - decoration: InputDecoration(labelText: AppLocalizations.of(context).username), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.username), autofillHints: [AutofillHints.username], controller: _usernameController, textInputAction: TextInputAction.next, keyboardType: TextInputType.emailAddress, validator: (value) { - if (value.isEmpty) { - return AppLocalizations.of(context).invalidUsername; + if (value!.isEmpty) { + return AppLocalizations.of(context)!.invalidUsername; } return null; }, onSaved: (value) { - _authData['username'] = value; + _authData['username'] = value!; }, ), if (_authMode == AuthMode.Signup) TextFormField( key: Key('inputEmail'), - decoration: InputDecoration(labelText: AppLocalizations.of(context).email), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.email), autofillHints: [AutofillHints.email], controller: _emailController, keyboardType: TextInputType.emailAddress, @@ -216,44 +214,44 @@ class _AuthCardState extends State { // Email is not required validator: (value) { - if (value.isNotEmpty && !value.contains('@')) { - return AppLocalizations.of(context).invalidEmail; + if (value!.isNotEmpty && !value.contains('@')) { + return AppLocalizations.of(context)!.invalidEmail; } return null; }, onSaved: (value) { - _authData['email'] = value; + _authData['email'] = value!; }, ), TextFormField( key: Key('inputPassword'), - decoration: InputDecoration(labelText: AppLocalizations.of(context).password), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.password), autofillHints: [AutofillHints.password], obscureText: true, controller: _passwordController, textInputAction: TextInputAction.next, validator: (value) { - if (value.isEmpty || value.length < 8) { - return AppLocalizations.of(context).passwordTooShort; + if (value!.isEmpty || value.length < 8) { + return AppLocalizations.of(context)!.passwordTooShort; } return null; }, onSaved: (value) { - _authData['password'] = value; + _authData['password'] = value!; }, ), if (_authMode == AuthMode.Signup) TextFormField( key: Key('inputPassword2'), decoration: - InputDecoration(labelText: AppLocalizations.of(context).confirmPassword), + InputDecoration(labelText: AppLocalizations.of(context)!.confirmPassword), controller: _password2Controller, enabled: _authMode == AuthMode.Signup, obscureText: true, validator: _authMode == AuthMode.Signup ? (value) { if (value != _passwordController.text) { - return AppLocalizations.of(context).passwordsDontMatch; + return AppLocalizations.of(context)!.passwordsDontMatch; } return null; } @@ -270,22 +268,22 @@ class _AuthCardState extends State { child: TextFormField( key: Key('inputServer'), decoration: InputDecoration( - labelText: AppLocalizations.of(context).customServerUrl, - helperText: AppLocalizations.of(context).customServerHint, + labelText: AppLocalizations.of(context)!.customServerUrl, + helperText: AppLocalizations.of(context)!.customServerHint, helperMaxLines: 4), controller: _serverUrlController, validator: (value) { - if (Uri.tryParse(value) == null) { - return AppLocalizations.of(context).invalidUrl; + if (Uri.tryParse(value!) == null) { + return AppLocalizations.of(context)!.invalidUrl; } if (value.isEmpty || !value.contains('http')) { - return AppLocalizations.of(context).invalidUrl; + return AppLocalizations.of(context)!.invalidUrl; } return null; }, onSaved: (value) { - _authData['serverUrl'] = value; + _authData['serverUrl'] = value!; }, ), ), @@ -301,7 +299,7 @@ class _AuthCardState extends State { _serverUrlController.text = DEFAULT_SERVER; }, ), - Text(AppLocalizations.of(context).reset) + Text(AppLocalizations.of(context)!.reset) ], ), ], @@ -316,8 +314,8 @@ class _AuthCardState extends State { ElevatedButton( key: Key('actionButton'), child: Text(_authMode == AuthMode.Login - ? AppLocalizations.of(context).login - : AppLocalizations.of(context).register), + ? AppLocalizations.of(context)!.login + : AppLocalizations.of(context)!.register), onPressed: () { return _submit(context); }, @@ -326,15 +324,15 @@ class _AuthCardState extends State { key: Key('toggleActionButton'), child: Text( _authMode == AuthMode.Login - ? AppLocalizations.of(context).registerInstead.toUpperCase() - : AppLocalizations.of(context).loginInstead.toUpperCase(), + ? AppLocalizations.of(context)!.registerInstead.toUpperCase() + : AppLocalizations.of(context)!.loginInstead.toUpperCase(), ), onPressed: _switchAuthMode, ), TextButton( child: Text(_hideCustomServer - ? AppLocalizations.of(context).useCustomServer - : AppLocalizations.of(context).useDefaultServer), + ? AppLocalizations.of(context)!.useCustomServer + : AppLocalizations.of(context)!.useDefaultServer), key: Key('toggleCustomServerButton'), onPressed: () { setState(() { diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index a69bcd93a..301704877 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -39,7 +39,7 @@ class DashboardScreen extends StatefulWidget { class _DashboardScreenState extends State { Widget getAppBar() { return AppBar( - title: Text(AppLocalizations.of(context).labelDashboard), + title: Text(AppLocalizations.of(context)!.labelDashboard), actions: [], ); } @@ -64,7 +64,7 @@ class _DashboardScreenState extends State { await workoutProvider.fetchAndSetWorkouts(); await workoutProvider.setAllFullWorkouts(); if (workoutProvider.activePlan != null) { - workoutProvider.setCurrentPlan(workoutProvider.activePlan.id); + workoutProvider.setCurrentPlan(workoutProvider.activePlan!.id!); } // Weight @@ -76,7 +76,7 @@ class _DashboardScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: getAppBar(), + appBar: getAppBar() as PreferredSizeWidget?, drawer: AppDrawer(), body: FutureBuilder( future: _loadEntries(context), @@ -86,7 +86,7 @@ class _DashboardScreenState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ Text( - AppLocalizations.of(context).loadingText, + AppLocalizations.of(context)!.loadingText, style: Theme.of(context).textTheme.headline5, ), Padding(padding: EdgeInsets.symmetric(vertical: 8)), diff --git a/lib/screens/gym_mode.dart b/lib/screens/gym_mode.dart index 8a58e2e10..2959fdab1 100644 --- a/lib/screens/gym_mode.dart +++ b/lib/screens/gym_mode.dart @@ -32,7 +32,7 @@ class GymModeScreen extends StatefulWidget { class _GymModeScreenState extends State { @override Widget build(BuildContext context) { - final _day = ModalRoute.of(context).settings.arguments as Day; + final _day = ModalRoute.of(context)!.settings.arguments as Day; return Scaffold( body: Consumer( diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 54795b50c..3d03b2e7c 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -31,7 +31,7 @@ class HomeTabsScreen extends StatefulWidget { } class _HomeTabsScreenState extends State with SingleTickerProviderStateMixin { - TabController controller; + TabController? controller; @override initState() { diff --git a/lib/screens/nutritional_plan_screen.dart b/lib/screens/nutritional_plan_screen.dart index 667346807..5a06507a5 100644 --- a/lib/screens/nutritional_plan_screen.dart +++ b/lib/screens/nutritional_plan_screen.dart @@ -36,7 +36,7 @@ class NutritionalPlanScreen extends StatelessWidget { @override Widget build(BuildContext context) { - final _nutritionalPlan = ModalRoute.of(context).settings.arguments as NutritionalPlan; + final _nutritionalPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan /*!*/; return Scaffold( //appBar: getAppBar(nutritionalPlan), @@ -55,14 +55,14 @@ class NutritionalPlanScreen extends StatelessWidget { if (value == NutritionalPlanOptions.edit) { showFormBottomSheet( context, - AppLocalizations.of(context).edit, + AppLocalizations.of(context)!.edit, PlanForm(_nutritionalPlan), ); // Delete } else if (value == NutritionalPlanOptions.delete) { Provider.of(context, listen: false) - .deletePlan(_nutritionalPlan.id); + .deletePlan(_nutritionalPlan.id!); Navigator.of(context).pushNamed(NutritionalPlanScreen.routeName); } }, @@ -70,12 +70,12 @@ class NutritionalPlanScreen extends StatelessWidget { return [ PopupMenuItem( value: NutritionalPlanOptions.edit, - child: Text(AppLocalizations.of(context).edit), + child: Text(AppLocalizations.of(context)!.edit), ), const PopupMenuDivider(), PopupMenuItem( value: NutritionalPlanOptions.delete, - child: Text(AppLocalizations.of(context).delete), + child: Text(AppLocalizations.of(context)!.delete), ), ]; }, diff --git a/lib/screens/nutritional_plans_screen.dart b/lib/screens/nutritional_plans_screen.dart index 8f3ff46d7..3b9a258c6 100644 --- a/lib/screens/nutritional_plans_screen.dart +++ b/lib/screens/nutritional_plans_screen.dart @@ -19,7 +19,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; -import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/widgets/app_drawer.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; @@ -36,22 +35,22 @@ class NutritionScreen extends StatefulWidget { class _NutritionScreenState extends State { Widget getAppBar() { return AppBar( - title: Text(AppLocalizations.of(context).nutritionalPlans), + title: Text(AppLocalizations.of(context)!.nutritionalPlans), ); } @override Widget build(BuildContext context) { return Scaffold( - appBar: getAppBar(), + appBar: getAppBar() as PreferredSizeWidget?, drawer: AppDrawer(), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () async { showFormBottomSheet( context, - AppLocalizations.of(context).newNutritionalPlan, - PlanForm(NutritionalPlan()), + AppLocalizations.of(context)!.newNutritionalPlan, + PlanForm(), ); //await showNutritionalPlanSheet(context, nutritionalPlan); }, diff --git a/lib/screens/weight_screen.dart b/lib/screens/weight_screen.dart index 3a7a69334..00d10f471 100644 --- a/lib/screens/weight_screen.dart +++ b/lib/screens/weight_screen.dart @@ -33,21 +33,21 @@ class WeightScreen extends StatefulWidget { class _WeightScreenState extends State { Widget getAppBar() { return AppBar( - title: Text(AppLocalizations.of(context).weight), + title: Text(AppLocalizations.of(context)!.weight), ); } @override Widget build(BuildContext context) { return Scaffold( - appBar: getAppBar(), + appBar: getAppBar() as PreferredSizeWidget?, drawer: AppDrawer(), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () async { showFormBottomSheet( context, - AppLocalizations.of(context).newEntry, + AppLocalizations.of(context)!.newEntry, WeightForm(), ); }, diff --git a/lib/screens/workout_plan_screen.dart b/lib/screens/workout_plan_screen.dart index b03cb2d69..b0037215c 100644 --- a/lib/screens/workout_plan_screen.dart +++ b/lib/screens/workout_plan_screen.dart @@ -64,14 +64,14 @@ class _WorkoutPlanScreenState extends State { return WorkoutLogs(plan, _changeMode); break; case WorkoutScreenMode.gym: - return Text(AppLocalizations.of(context).gymMode); + return Text(AppLocalizations.of(context)!.gymMode); break; } } @override Widget build(BuildContext context) { - final workoutPlan = ModalRoute.of(context).settings.arguments as WorkoutPlan; + final workoutPlan = ModalRoute.of(context)!.settings.arguments as WorkoutPlan; return Scaffold( //appBar: getAppBar(workoutPlan), @@ -96,14 +96,14 @@ class _WorkoutPlanScreenState extends State { if (value == WorkoutOptions.edit) { showFormBottomSheet( context, - AppLocalizations.of(context).edit, + AppLocalizations.of(context)!.edit, WorkoutForm(workoutPlan), ); // Delete } else if (value == WorkoutOptions.delete) { Provider.of(context, listen: false) - .deleteWorkout(workoutPlan.id); + .deleteWorkout(workoutPlan.id!); Navigator.of(context).pushNamed(WorkoutPlansScreen.routeName); // Toggle Mode @@ -119,7 +119,7 @@ class _WorkoutPlanScreenState extends State { return [ PopupMenuItem( value: WorkoutOptions.edit, - child: Text(AppLocalizations.of(context).edit), + child: Text(AppLocalizations.of(context)!.edit), ), PopupMenuItem( child: _mode == WorkoutScreenMode.log @@ -130,7 +130,7 @@ class _WorkoutPlanScreenState extends State { const PopupMenuDivider(), PopupMenuItem( value: WorkoutOptions.delete, - child: Text(AppLocalizations.of(context).delete), + child: Text(AppLocalizations.of(context)!.delete), ), ]; }, diff --git a/lib/screens/workout_plans_screen.dart b/lib/screens/workout_plans_screen.dart index df7fac8ee..ace75a14f 100644 --- a/lib/screens/workout_plans_screen.dart +++ b/lib/screens/workout_plans_screen.dart @@ -24,6 +24,7 @@ import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/providers/workout_plans.dart'; import 'package:wger/widgets/app_drawer.dart'; import 'package:wger/widgets/core/bottom_sheet.dart'; +import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/workouts/forms.dart'; import 'package:wger/widgets/workouts/workout_plans_list.dart'; @@ -35,23 +36,17 @@ class WorkoutPlansScreen extends StatefulWidget { } class _WorkoutPlansScreenState extends State { - Widget getAppBar() { - return AppBar( - title: Text(AppLocalizations.of(context).labelWorkoutPlans), - ); - } - @override Widget build(BuildContext context) { return Scaffold( - appBar: getAppBar(), + appBar: WgerAppBar(AppLocalizations.of(context)!.labelWorkoutPlans), drawer: AppDrawer(), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () { showFormBottomSheet( context, - AppLocalizations.of(context).newWorkout, + AppLocalizations.of(context)!.newWorkout, WorkoutForm(WorkoutPlan()), ); }, diff --git a/lib/widgets/app_drawer.dart b/lib/widgets/app_drawer.dart index 610888d2c..4c0d6e438 100644 --- a/lib/widgets/app_drawer.dart +++ b/lib/widgets/app_drawer.dart @@ -38,7 +38,7 @@ class AppDrawer extends StatelessWidget { /* ListTile( leading: Icon(Icons.home), - title: Text(AppLocalizations.of(context).labelDashboard), + title: Text(AppLocalizations.of(context)!.labelDashboard), onTap: () { Navigator.of(context).pop(); Navigator.of(context).pushReplacementNamed(DashboardScreen.routeName); @@ -114,7 +114,7 @@ class AppDrawer extends StatelessWidget { //dense: true, icon: Icon(Icons.info), applicationName: 'wger', - applicationVersion: '${authProvider.applicationVersion.version} ' + applicationVersion: '${authProvider.applicationVersion!.version} ' '(server: ${authProvider.serverVersion})', applicationLegalese: '\u{a9} 2020 - 2021 contributors', applicationIcon: Padding( @@ -133,7 +133,7 @@ class AppDrawer extends StatelessWidget { style: TextStyle(fontSize: 16, color: Colors.black), children: [ TextSpan( - text: AppLocalizations.of(context).aboutText, + text: AppLocalizations.of(context)!.aboutText, ), TextSpan( text: 'https://github.com/wger-project', diff --git a/lib/widgets/core/bottom_sheet.dart b/lib/widgets/core/bottom_sheet.dart index accb401b5..4481e9165 100644 --- a/lib/widgets/core/bottom_sheet.dart +++ b/lib/widgets/core/bottom_sheet.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; -Future showFormBottomSheet(BuildContext context, String header, Widget form, +Future showFormBottomSheet(BuildContext context, String header, Widget form, {bool scrollControlled: false}) async { return showModalBottomSheet( isScrollControlled: scrollControlled, diff --git a/lib/widgets/core/core.dart b/lib/widgets/core/core.dart index 690df39ce..ee041f5ec 100644 --- a/lib/widgets/core/core.dart +++ b/lib/widgets/core/core.dart @@ -23,7 +23,7 @@ class MutedText extends StatelessWidget { String _text; MutedText( this._text, { - Key key, + Key? key, }) : super(key: key); @override @@ -31,3 +31,20 @@ class MutedText extends StatelessWidget { return Text(_text, style: TextStyle(color: wgerTextMuted)); } } + +/// Appbar that extends [PreferredSizeWidget] +class WgerAppBar extends StatelessWidget with PreferredSizeWidget { + String _title; + + WgerAppBar(this._title); + + @override + Widget build(BuildContext context) { + return AppBar( + title: Text(_title), + ); + } + + @override + Size get preferredSize => Size.fromHeight(kToolbarHeight); +} diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index 9b47a3b25..a710f47f7 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -64,7 +64,7 @@ class Event { } class DashboardCalendarWidget extends StatefulWidget { - DashboardCalendarWidget({Key key}) : super(key: key); + DashboardCalendarWidget(); @override _DashboardCalendarWidgetState createState() => _DashboardCalendarWidgetState(); @@ -72,10 +72,10 @@ class DashboardCalendarWidget extends StatefulWidget { class _DashboardCalendarWidgetState extends State with TickerProviderStateMixin { - Map _events; - List _selectedEvents; - AnimationController _animationController; - CalendarController _calendarController; + late Map _events; + late List _selectedEvents; + late AnimationController _animationController; + late CalendarController _calendarController; @override void initState() { @@ -115,7 +115,7 @@ class _DashboardCalendarWidgetState extends State } // Add events to lists - _events[date].add(Event(EventType.weight, '${entry.weight} kg')); + _events[date]!.add(Event(EventType.weight, '${entry.weight} kg')); } // Process workout sessions @@ -134,9 +134,9 @@ class _DashboardCalendarWidgetState extends State } // Add events to lists - _events[date].add(Event( + _events[date]!.add(Event( EventType.session, - '${AppLocalizations.of(context).impression}: ${session.impressionAsString} $time', + '${AppLocalizations.of(context)!.impression}: ${session.impressionAsString} $time', )); } }); @@ -151,7 +151,7 @@ class _DashboardCalendarWidgetState extends State } // Add events to lists - _events[date].add(Event( + _events[date]!.add(Event( EventType.caloriesDiary, '${entry.value.energy.toStringAsFixed(0)} kcal', )); @@ -186,7 +186,7 @@ class _DashboardCalendarWidgetState extends State children: [ const SizedBox(height: 8.0), Text( - AppLocalizations.of(context).calendar, + AppLocalizations.of(context)!.calendar, style: Theme.of(context).textTheme.headline4, ), @@ -361,7 +361,7 @@ class _DashboardCalendarWidgetState extends State mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( - child: Text(AppLocalizations.of(context).goToToday), + child: Text(AppLocalizations.of(context)!.goToToday), onPressed: () async { final today = DateTime.now(); _calendarController.setSelectedDay( @@ -399,13 +399,13 @@ class _DashboardCalendarWidgetState extends State title: Text((() { switch (event.type) { case EventType.caloriesDiary: - return AppLocalizations.of(context).nutritionalDiary; + return AppLocalizations.of(context)!.nutritionalDiary; case EventType.session: - return AppLocalizations.of(context).workoutSession; + return AppLocalizations.of(context)!.workoutSession; case EventType.weight: - return AppLocalizations.of(context).weight; + return AppLocalizations.of(context)!.weight; } return event.description.toString(); })()), diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 5367a81d6..83d6aa47d 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -38,9 +38,8 @@ import 'package:wger/widgets/workouts/forms.dart'; class DashboardNutritionWidget extends StatefulWidget { const DashboardNutritionWidget({ - Key key, - @required this.context, - }) : super(key: key); + required this.context, + }); final BuildContext context; @@ -49,13 +48,13 @@ class DashboardNutritionWidget extends StatefulWidget { } class _DashboardNutritionWidgetState extends State { - Nutrition nutrition; - NutritionalPlan plan; + //Nutrition nutrition; + late NutritionalPlan plan; var showDetail = false; @override Widget build(BuildContext context) { - plan = Provider.of(context, listen: false).currentPlan; + NutritionalPlan? plan = Provider.of(context, listen: false).currentPlan; final bool hasContent = plan != null; List out = []; @@ -70,16 +69,16 @@ class _DashboardNutritionWidgetState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - '${meal.nutritionalValues.energy.toStringAsFixed(0)}${AppLocalizations.of(context).kcal}'), + '${meal.nutritionalValues.energy.toStringAsFixed(0)}${AppLocalizations.of(context)!.kcal}'), Text(' / '), Text( - '${meal.nutritionalValues.protein.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + '${meal.nutritionalValues.protein.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'), Text(' / '), Text( - '${meal.nutritionalValues.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + '${meal.nutritionalValues.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'), Text(' / '), Text( - '${meal.nutritionalValues.fat.toStringAsFixed(0)}${AppLocalizations.of(context).g} '), + '${meal.nutritionalValues.fat.toStringAsFixed(0)}${AppLocalizations.of(context)!.g} '), ], )); out.add(SizedBox(height: 5)); @@ -93,7 +92,7 @@ class _DashboardNutritionWidgetState extends State { children: [ Text(item.ingredientObj.name), SizedBox(width: 5), - Text('${item.amount.toString()} ${AppLocalizations.of(context).g}'), + Text('${item.amount.toString()} ${AppLocalizations.of(context)!.g}'), ], ), ]), @@ -110,7 +109,7 @@ class _DashboardNutritionWidgetState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - AppLocalizations.of(context).nutritionalPlan, + AppLocalizations.of(context)!.nutritionalPlan, style: Theme.of(context).textTheme.headline4, ), hasContent @@ -127,7 +126,7 @@ class _DashboardNutritionWidgetState extends State { style: TextStyle(fontSize: 20), ), onPressed: () { - return Navigator.of(context) + Navigator.of(context) .pushNamed(NutritionalPlanScreen.routeName, arguments: plan); }, ), @@ -140,15 +139,15 @@ class _DashboardNutritionWidgetState extends State { ], ) : NothingFound( - AppLocalizations.of(context).noNutritionalPlans, - AppLocalizations.of(context).newNutritionalPlan, - PlanForm(NutritionalPlan()), + AppLocalizations.of(context)!.noNutritionalPlans, + AppLocalizations.of(context)!.newNutritionalPlan, + PlanForm(), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( - child: Text(AppLocalizations.of(context).toggleDetails), + child: Text(AppLocalizations.of(context)!.toggleDetails), onPressed: () { setState(() { showDetail = !showDetail; @@ -165,9 +164,8 @@ class _DashboardNutritionWidgetState extends State { class DashboardWeightWidget extends StatefulWidget { const DashboardWeightWidget({ - Key key, - @required this.context, - }) : super(key: key); + required this.context, + }); final BuildContext context; @@ -176,7 +174,7 @@ class DashboardWeightWidget extends StatefulWidget { } class _DashboardWeightWidgetState extends State { - BodyWeight weightEntriesData; + late BodyWeight weightEntriesData; @override Widget build(BuildContext context) { @@ -187,7 +185,7 @@ class _DashboardWeightWidgetState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - AppLocalizations.of(context).weight, + AppLocalizations.of(context)!.weight, style: Theme.of(context).textTheme.headline4, ), Column( @@ -199,19 +197,19 @@ class _DashboardWeightWidgetState extends State { child: WeightChartWidget(weightEntriesData.items), ) : NothingFound( - AppLocalizations.of(context).noWeightEntries, - AppLocalizations.of(context).newEntry, + AppLocalizations.of(context)!.noWeightEntries, + AppLocalizations.of(context)!.newEntry, WeightForm(), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( - child: Text(AppLocalizations.of(context).newEntry), + child: Text(AppLocalizations.of(context)!.newEntry), onPressed: () async { showFormBottomSheet( context, - AppLocalizations.of(context).newEntry, + AppLocalizations.of(context)!.newEntry, WeightForm(), ); }, @@ -228,9 +226,8 @@ class _DashboardWeightWidgetState extends State { class DashboardWorkoutWidget extends StatefulWidget { DashboardWorkoutWidget({ - Key key, - @required this.context, - }) : super(key: key); + required this.context, + }); final BuildContext context; @@ -239,7 +236,7 @@ class DashboardWorkoutWidget extends StatefulWidget { } class _DashboardWorkoutWidgetState extends State { - WorkoutPlan _workoutPlan; + late WorkoutPlan _workoutPlan; var showDetail = false; @override @@ -250,7 +247,7 @@ class _DashboardWorkoutWidgetState extends State { @override Widget build(BuildContext context) { - _workoutPlan = Provider.of(context, listen: false).activePlan; + WorkoutPlan? _workoutPlan = Provider.of(context, listen: false).activePlan; final bool hasContent = _workoutPlan != null; List out = []; @@ -286,7 +283,7 @@ class _DashboardWorkoutWidgetState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - AppLocalizations.of(context).labelWorkoutPlan, + AppLocalizations.of(context)!.labelWorkoutPlan, style: Theme.of(context).textTheme.headline4, ), hasContent @@ -303,7 +300,7 @@ class _DashboardWorkoutWidgetState extends State { style: TextStyle(fontSize: 20), ), onPressed: () { - return Navigator.of(context) + Navigator.of(context) .pushNamed(WorkoutPlanScreen.routeName, arguments: _workoutPlan); }, ), @@ -311,15 +308,15 @@ class _DashboardWorkoutWidgetState extends State { ], ) : NothingFound( - AppLocalizations.of(context).noWorkoutPlans, - AppLocalizations.of(context).newWorkout, + AppLocalizations.of(context)!.noWorkoutPlans, + AppLocalizations.of(context)!.newWorkout, WorkoutForm(WorkoutPlan()), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( - child: Text(AppLocalizations.of(context).toggleDetails), + child: Text(AppLocalizations.of(context)!.toggleDetails), onPressed: () { setState(() { showDetail = !showDetail; diff --git a/lib/widgets/nutrition/charts.dart b/lib/widgets/nutrition/charts.dart index 3e44fe5c1..3a072fa58 100644 --- a/lib/widgets/nutrition/charts.dart +++ b/lib/widgets/nutrition/charts.dart @@ -17,6 +17,7 @@ */ import 'package:charts_flutter/flutter.dart' as charts; +import 'package:charts_flutter/flutter.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; @@ -44,12 +45,12 @@ class NutritionalPlanPieChartWidget extends StatelessWidget { domainFn: (datum, index) => datum[0], measureFn: (datum, index) => datum[1], data: [ - [AppLocalizations.of(context).protein, _nutritionalValues.protein], - [AppLocalizations.of(context).fat, _nutritionalValues.fat], - [AppLocalizations.of(context).carbohydrates, _nutritionalValues.carbohydrates], + [AppLocalizations.of(context)!.protein, _nutritionalValues.protein], + [AppLocalizations.of(context)!.fat, _nutritionalValues.fat], + [AppLocalizations.of(context)!.carbohydrates, _nutritionalValues.carbohydrates], ], labelAccessorFn: (List row, _) => - '${row[0]}, ${row[1].toStringAsFixed(0)}${AppLocalizations.of(context).g}', + '${row[0]}, ${row[1].toStringAsFixed(0)}${AppLocalizations.of(context)!.g}', ) ], defaultRenderer: new charts.ArcRendererConfig( @@ -62,26 +63,26 @@ class NutritionalPlanPieChartWidget extends StatelessWidget { class NutritionalDiaryChartWidget extends StatelessWidget { const NutritionalDiaryChartWidget({ - Key key, - @required NutritionalPlan nutritionalPlan, - }) : _nutritionalPlan = nutritionalPlan, + Key? key, + required NutritionalPlan? nutritionalPlan, + }) : _nutritionalPlan = nutritionalPlan, super(key: key); - final NutritionalPlan _nutritionalPlan; + final NutritionalPlan? _nutritionalPlan; @override Widget build(BuildContext context) { return charts.TimeSeriesChart( [ - charts.Series, DateTime>( + charts.Series, DateTime?>( id: 'NutritionDiary', colorFn: (datum, index) => wgerChartSecondaryColor, domainFn: (datum, index) => datum[1], measureFn: (datum, index) => datum[0].energy, - data: _nutritionalPlan.logEntriesValues.keys - .map((e) => [_nutritionalPlan.logEntriesValues[e], e]) + data: _nutritionalPlan!.logEntriesValues.keys + .map((e) => [_nutritionalPlan!.logEntriesValues[e], e]) .toList(), - ) + ) as Series ], defaultRenderer: new charts.BarRendererConfig(), ); diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index b831f1ae0..07707417f 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -29,20 +29,31 @@ import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/providers/nutrition.dart'; class MealForm extends StatelessWidget { - Meal _meal; + late Meal _meal; int _planId; + //var _mealData = {'id': null, 'planId': -1, 'time': TimeOfDay.now()}; final _form = GlobalKey(); final _timeController = TextEditingController(); - MealForm(planId, [meal]) { - this._planId = planId; - this._meal = meal ?? Meal(); - - _timeController.text = - _meal.time != null ? timeToString(_meal.time) : timeToString(TimeOfDay.now()); + MealForm(this._planId, [meal]) { + this._meal = meal ?? Meal(plan: _planId); + _timeController.text = timeToString(_meal.time)!; } + /* + MealForm(int planId, [Meal? meal]) { + _mealData['planId'] = planId; + _timeController.text = timeToString(_mealData['time'] as TimeOfDay)!; + + if (meal != null) { + _mealData['id'] = meal.id; + _mealData['time'] = meal.time; + _timeController.text = timeToString(meal.time)!; + } + } + */ + @override Widget build(BuildContext context) { return Container( @@ -52,7 +63,7 @@ class MealForm extends StatelessWidget { child: Column( children: [ TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).time), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.time), controller: _timeController, onTap: () async { // Stop keyboard from appearing @@ -61,10 +72,10 @@ class MealForm extends StatelessWidget { // Open time picker var pickedTime = await showTimePicker( context: context, - initialTime: _meal.time ?? TimeOfDay.now(), + initialTime: _meal.time, ); - _timeController.text = timeToString(pickedTime); + _timeController.text = timeToString(pickedTime)!; }, onSaved: (newValue) { _meal.time = stringToTime(newValue); @@ -72,14 +83,12 @@ class MealForm extends StatelessWidget { onFieldSubmitted: (_) {}, ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { - if (!_form.currentState.validate()) { + if (!_form.currentState!.validate()) { return; } - _form.currentState.save(); - - _meal.plan = _planId; + _form.currentState!.save(); try { _meal.id == null @@ -101,14 +110,27 @@ class MealForm extends StatelessWidget { } class MealItemForm extends StatelessWidget { - Meal meal; - MealItem mealItem; + Meal _meal; + late MealItem _mealItem; - MealItemForm(meal, [mealItem]) { - this.meal = meal; - this.mealItem = mealItem ?? MealItem(); + //var mealItemData = {}; + + MealItemForm(this._meal, [mealItem]) { + this._mealItem = mealItem ?? MealItem(meal: _meal.id); } + /* + MealItemForm(this._meal, [MealItem? mealItem]) { + //this.meal = meal; + mealItemData['meal'] = _meal.id; + if (mealItem != null) { + mealItemData['ingredientId'] = mealItem.ingredientId; + mealItemData['amount'] = mealItem.amount; + } + //this.mealItem = mealItem ?? MealItem(); + } + */ + final _form = GlobalKey(); final _ingredientController = TextEditingController(); final _amountController = TextEditingController(); @@ -124,13 +146,13 @@ class MealItemForm extends StatelessWidget { TypeAheadFormField( textFieldConfiguration: TextFieldConfiguration( controller: this._ingredientController, - decoration: InputDecoration(labelText: AppLocalizations.of(context).ingredient), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.ingredient), ), suggestionsCallback: (pattern) async { return await Provider.of(context, listen: false) .searchIngredient(pattern); }, - itemBuilder: (context, suggestion) { + itemBuilder: (context, dynamic suggestion) { return ListTile( title: Text(suggestion['value']), subtitle: Text(suggestion['data']['id'].toString()), @@ -139,49 +161,47 @@ class MealItemForm extends StatelessWidget { transitionBuilder: (context, suggestionsBox, controller) { return suggestionsBox; }, - onSuggestionSelected: (suggestion) { - mealItem.ingredientId = suggestion['data']['id']; + onSuggestionSelected: (dynamic suggestion) { + _mealItem.ingredientId = suggestion['data']['id']; this._ingredientController.text = suggestion['value']; }, validator: (value) { - if (value.isEmpty) { - return AppLocalizations.of(context).selectIngredient; + if (value!.isEmpty) { + return AppLocalizations.of(context)!.selectIngredient; } - if (mealItem.ingredientId == null) { - return AppLocalizations.of(context).selectIngredient; + if (_mealItem.ingredientId == null) { + return AppLocalizations.of(context)!.selectIngredient; } return null; }, ), TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).amount), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.amount), controller: _amountController, keyboardType: TextInputType.number, onFieldSubmitted: (_) {}, onSaved: (newValue) { - mealItem.amount = double.parse(newValue); + _mealItem.amount = double.parse(newValue!); }, validator: (value) { try { - double.parse(value); + double.parse(value!); } catch (error) { - return AppLocalizations.of(context).enterValidNumber; + return AppLocalizations.of(context)!.enterValidNumber; } return null; }, ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { - if (!_form.currentState.validate()) { + if (!_form.currentState!.validate()) { return; } - _form.currentState.save(); + _form.currentState!.save(); try { - mealItem.meal = meal.id; - - Provider.of(context, listen: false).addMealItem(mealItem, meal.id); + Provider.of(context, listen: false).addMealItem(_mealItem, _meal.id!); } on WgerHttpException catch (error) { showHttpExceptionErrorDialog(error, context); } catch (error) { @@ -198,45 +218,63 @@ class MealItemForm extends StatelessWidget { } class PlanForm extends StatelessWidget { - NutritionalPlan _plan; - PlanForm(this._plan); + //NutritionalPlan? _plan; + var _planData = { + 'description': '', + 'creationDate': DateTime.now(), + 'id': null, + }; final _form = GlobalKey(); - final descriptionController = TextEditingController(); + final _descriptionController = TextEditingController(); + + PlanForm([NutritionalPlan? plan]) { + if (plan != null) { + _planData['id'] = plan.id; + _planData['description'] = plan.description; + _planData['creationDate'] = plan.creationDate; + } + + _descriptionController.text = _planData['description'] as String; + } @override Widget build(BuildContext context) { - descriptionController.text = _plan.description ?? ''; - return Form( key: _form, child: Column( children: [ // Description TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).description), - controller: descriptionController, + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.description), + controller: _descriptionController, onFieldSubmitted: (_) {}, onSaved: (newValue) { - _plan.description = newValue; + _planData['description'] = newValue!; }, ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { // Validate and save the current values to the weightEntry - final isValid = _form.currentState.validate(); + final isValid = _form.currentState!.validate(); if (!isValid) { return; } - _form.currentState.save(); + _form.currentState!.save(); // Save the entry on the server try { - if (_plan.id != null) { - await Provider.of(context, listen: false).patchPlan(_plan); + NutritionalPlan plan = NutritionalPlan( + description: _planData['description'] as String, + creationDate: _planData['creationDate'] as DateTime, + ); + + if (_planData['id'] != null) { + plan.id = _planData['id'] as int; + await Provider.of(context, listen: false).patchPlan(plan); } else { - await Provider.of(context, listen: false).postPlan(_plan); + await Provider.of(context, listen: false).postPlan(plan); } // Saving was successful, reset the data diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index 8b04f59b7..b46782896 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -61,20 +61,20 @@ class _MealWidgetState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - MutedText(AppLocalizations.of(context).energy), - MutedText(AppLocalizations.of(context).protein), - MutedText(AppLocalizations.of(context).carbohydrates), - MutedText(AppLocalizations.of(context).fat), + MutedText(AppLocalizations.of(context)!.energy), + MutedText(AppLocalizations.of(context)!.protein), + MutedText(AppLocalizations.of(context)!.carbohydrates), + MutedText(AppLocalizations.of(context)!.fat), ], ), ), ...widget._meal.mealItems.map((item) => MealItemWidget(item, _expanded)).toList(), OutlinedButton( - child: Text(AppLocalizations.of(context).addIngredient), + child: Text(AppLocalizations.of(context)!.addIngredient), onPressed: () { showFormBottomSheet( context, - AppLocalizations.of(context).addIngredient, + AppLocalizations.of(context)!.addIngredient, MealItemForm(widget._meal), scrollControlled: true, ); @@ -96,8 +96,8 @@ class MealItemWidget extends StatelessWidget { @override Widget build(BuildContext context) { String unit = _item.weightUnit == null - ? AppLocalizations.of(context).g - : _item.weightUnit.weightUnit.name; + ? AppLocalizations.of(context)!.g + : _item.weightUnit!.weightUnit.name; final values = _item.nutritionalValues; return Container( @@ -127,7 +127,7 @@ class MealItemWidget extends StatelessWidget { Scaffold.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context)!.successfullyDeleted, textAlign: TextAlign.center, )), ); @@ -141,11 +141,11 @@ class MealItemWidget extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ MutedText( - '${values.energy.toStringAsFixed(0)} ${AppLocalizations.of(context).kcal}'), - MutedText('${values.protein.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + '${values.energy.toStringAsFixed(0)} ${AppLocalizations.of(context)!.kcal}'), + MutedText('${values.protein.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'), MutedText( - '${values.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), - MutedText('${values.fat.toStringAsFixed(0)}${AppLocalizations.of(context).g}'), + '${values.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'), + MutedText('${values.fat.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'), ], ), ], @@ -161,10 +161,8 @@ class DismissibleMealHeader extends StatelessWidget { const DismissibleMealHeader( this._expanded, this._toggle, { - Key key, - @required Meal meal, - }) : _meal = meal, - super(key: key); + required Meal meal, + }) : _meal = meal; final Meal _meal; @@ -174,7 +172,7 @@ class DismissibleMealHeader extends StatelessWidget { onLongPress: () { showFormBottomSheet( context, - AppLocalizations.of(context).edit, + AppLocalizations.of(context)!.edit, MealForm(_meal.plan, _meal), ); }, @@ -243,7 +241,7 @@ class DismissibleMealHeader extends StatelessWidget { Scaffold.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context)!.successfullyDeleted, textAlign: TextAlign.center, ), ), @@ -255,7 +253,7 @@ class DismissibleMealHeader extends StatelessWidget { Scaffold.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).mealLogged, + AppLocalizations.of(context)!.mealLogged, textAlign: TextAlign.center, ), ), diff --git a/lib/widgets/nutrition/nutritional_plan_detail.dart b/lib/widgets/nutrition/nutritional_plan_detail.dart index a95e4a723..39c9be0f4 100644 --- a/lib/widgets/nutrition/nutritional_plan_detail.dart +++ b/lib/widgets/nutrition/nutritional_plan_detail.dart @@ -42,12 +42,12 @@ class NutritionalPlanDetailWidget extends StatelessWidget { Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( - child: Text(AppLocalizations.of(context).addMeal), + child: Text(AppLocalizations.of(context)!.addMeal), onPressed: () { showFormBottomSheet( context, - AppLocalizations.of(context).addMeal, - MealForm(_nutritionalPlan.id), + AppLocalizations.of(context)!.addMeal, + MealForm(_nutritionalPlan.id!), ); }, ), @@ -67,14 +67,14 @@ class NutritionalPlanDetailWidget extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ - Text(AppLocalizations.of(context).energy), - Text(AppLocalizations.of(context).protein), - Text(AppLocalizations.of(context).carbohydrates), - Text(AppLocalizations.of(context).sugars), - Text(AppLocalizations.of(context).fat), - Text(AppLocalizations.of(context).saturatedFat), - Text(AppLocalizations.of(context).fibres), - Text(AppLocalizations.of(context).sodium), + Text(AppLocalizations.of(context)!.energy), + Text(AppLocalizations.of(context)!.protein), + Text(AppLocalizations.of(context)!.carbohydrates), + Text(AppLocalizations.of(context)!.sugars), + Text(AppLocalizations.of(context)!.fat), + Text(AppLocalizations.of(context)!.saturatedFat), + Text(AppLocalizations.of(context)!.fibres), + Text(AppLocalizations.of(context)!.sodium), ], ), ), @@ -97,14 +97,14 @@ class NutritionalPlanDetailWidget extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(AppLocalizations.of(context).kcal), - Text(AppLocalizations.of(context).g), - Text(AppLocalizations.of(context).g), - Text(AppLocalizations.of(context).g), - Text(AppLocalizations.of(context).g), - Text(AppLocalizations.of(context).g), - Text(AppLocalizations.of(context).g), - Text(AppLocalizations.of(context).g), + Text(AppLocalizations.of(context)!.kcal), + Text(AppLocalizations.of(context)!.g), + Text(AppLocalizations.of(context)!.g), + Text(AppLocalizations.of(context)!.g), + Text(AppLocalizations.of(context)!.g), + Text(AppLocalizations.of(context)!.g), + Text(AppLocalizations.of(context)!.g), + Text(AppLocalizations.of(context)!.g), ], ), ], @@ -130,17 +130,17 @@ class NutritionalPlanDetailWidget extends StatelessWidget { children: [ Text(''), Text( - '${AppLocalizations.of(context).energy} (${AppLocalizations.of(context).kcal})'), + '${AppLocalizations.of(context)!.energy} (${AppLocalizations.of(context)!.kcal})'), Text( - '${AppLocalizations.of(context).protein} (${AppLocalizations.of(context).g})'), + '${AppLocalizations.of(context)!.protein} (${AppLocalizations.of(context)!.g})'), Text( - '${AppLocalizations.of(context).carbohydrates} (${AppLocalizations.of(context).g})'), + '${AppLocalizations.of(context)!.carbohydrates} (${AppLocalizations.of(context)!.g})'), Text( - '${AppLocalizations.of(context).sugars} (${AppLocalizations.of(context).g})'), + '${AppLocalizations.of(context)!.sugars} (${AppLocalizations.of(context)!.g})'), Text( - '${AppLocalizations.of(context).fat} (${AppLocalizations.of(context).g})'), + '${AppLocalizations.of(context)!.fat} (${AppLocalizations.of(context)!.g})'), Text( - '${AppLocalizations.of(context).saturatedFat} (${AppLocalizations.of(context).g})'), + '${AppLocalizations.of(context)!.saturatedFat} (${AppLocalizations.of(context)!.g})'), ], ), ), diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index 9784a2ff7..a57502d08 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -37,26 +37,26 @@ class NutritionalPlansList extends StatelessWidget { key: Key(currentPlan.id.toString()), confirmDismiss: (direction) async { // Delete workout from DB - final bool res = await showDialog( + final bool? res = await showDialog( context: context, builder: (BuildContext contextDialog) { return AlertDialog( content: Text( - AppLocalizations.of(context).confirmDelete(currentPlan.description), + AppLocalizations.of(context)!.confirmDelete(currentPlan.description), ), actions: [ TextButton( - child: Text(AppLocalizations.of(context).cancel), + child: Text(AppLocalizations.of(context)!.cancel), onPressed: () => Navigator.of(contextDialog).pop(), ), TextButton( child: Text( - AppLocalizations.of(context).delete, + AppLocalizations.of(context)!.delete, style: TextStyle(color: Theme.of(context).errorColor), ), onPressed: () { // Confirmed, delete the workout - _nutritrionProvider.deletePlan(currentPlan.id); + _nutritrionProvider.deletePlan(currentPlan.id!); // Close the popup Navigator.of(contextDialog).pop(); @@ -65,7 +65,7 @@ class NutritionalPlansList extends StatelessWidget { Scaffold.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context)!.successfullyDeleted, textAlign: TextAlign.center, ), ), diff --git a/lib/widgets/weight/entries_list.dart b/lib/widgets/weight/entries_list.dart index 8cb1d2d12..ed8f0ee12 100644 --- a/lib/widgets/weight/entries_list.dart +++ b/lib/widgets/weight/entries_list.dart @@ -49,7 +49,7 @@ class WeightEntriesList extends StatelessWidget { onDismissed: (direction) { if (direction == DismissDirection.endToStart) { // Delete entry from DB - _weightProvider.deleteEntry(currentEntry.id); + _weightProvider.deleteEntry(currentEntry.id!); // and inform the user Scaffold.of(context).showSnackBar( @@ -67,7 +67,7 @@ class WeightEntriesList extends StatelessWidget { if (direction == DismissDirection.startToEnd) { showFormBottomSheet( context, - AppLocalizations.of(context).edit, + AppLocalizations.of(context)!.edit, WeightForm(currentEntry), ); return false; diff --git a/lib/widgets/weight/forms.dart b/lib/widgets/weight/forms.dart index aff44639a..12c56f926 100644 --- a/lib/widgets/weight/forms.dart +++ b/lib/widgets/weight/forms.dart @@ -13,11 +13,11 @@ class WeightForm extends StatelessWidget { final dateController = TextEditingController(text: toDate(DateTime.now()).toString()); final weightController = TextEditingController(); - WeightEntry _weightEntry; + late WeightEntry _weightEntry; - WeightForm([weightEntry]) { + WeightForm([WeightEntry? weightEntry]) { this._weightEntry = weightEntry ?? WeightEntry(); - weightController.text = _weightEntry.weight == null ? '' : _weightEntry.weight.toString(); + weightController.text = _weightEntry.id == null ? '' : _weightEntry.weight.toString(); } @override @@ -28,7 +28,7 @@ class WeightForm extends StatelessWidget { children: [ // Weight date TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).date), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.date), controller: dateController, onTap: () async { // Stop keyboard from appearing @@ -42,44 +42,44 @@ class WeightForm extends StatelessWidget { lastDate: DateTime.now(), ); - dateController.text = toDate(pickedDate); + dateController.text = toDate(pickedDate)!; }, onSaved: (newValue) { - _weightEntry.date = DateTime.parse(newValue); + _weightEntry.date = DateTime.parse(newValue!); }, onFieldSubmitted: (_) {}, ), // Weight TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).weight), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.weight), controller: weightController, keyboardType: TextInputType.number, onFieldSubmitted: (_) {}, onSaved: (newValue) { - _weightEntry.weight = double.parse(newValue); + _weightEntry.weight = double.parse(newValue!); }, validator: (value) { - if (value.isEmpty) { - return AppLocalizations.of(context).enterValue; + if (value!.isEmpty) { + return AppLocalizations.of(context)!.enterValue; } try { double.parse(value); } catch (error) { - return AppLocalizations.of(context).enterValidNumber; + return AppLocalizations.of(context)!.enterValidNumber; } return null; }, ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { // Validate and save the current values to the weightEntry - final isValid = _form.currentState.validate(); + final isValid = _form.currentState!.validate(); if (!isValid) { return; } - _form.currentState.save(); + _form.currentState!.save(); // Save the entry on the server try { diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 778f5fa2a..f0c9cf611 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -34,7 +34,7 @@ class SettingWidget extends StatelessWidget { final bool expanded; final toggle; - SettingWidget({this.setting, this.expanded, this.toggle}); + SettingWidget({required this.setting, required this.expanded, required this.toggle}); @override Widget build(BuildContext context) { @@ -134,7 +134,7 @@ class _WorkoutDayWidgetState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ Text( - AppLocalizations.of(context).gymMode, + AppLocalizations.of(context)!.gymMode, style: TextStyle(color: Colors.white), ), Icon( @@ -151,11 +151,11 @@ class _WorkoutDayWidgetState extends State { ) .toList(), OutlinedButton( - child: Text(AppLocalizations.of(context).addExercise), + child: Text(AppLocalizations.of(context)!.addExercise), onPressed: () { showFormBottomSheet( context, - AppLocalizations.of(context).newSet, + AppLocalizations.of(context)!.newSet, SetFormWidget(widget._day), scrollControlled: true, ); @@ -174,14 +174,12 @@ class DayHeaderDismissible extends StatelessWidget { final _toggle; const DayHeaderDismissible({ - Key key, - @required Day day, - @required bool expanded, - @required Function toggle, - }) : _day = day, + required Day day, + required bool expanded, + required Function toggle, + }) : _day = day, _expanded = expanded, - _toggle = toggle, - super(key: key); + _toggle = toggle; @override Widget build(BuildContext context) { @@ -254,7 +252,7 @@ class DayHeaderDismissible extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ Text( - AppLocalizations.of(context).gymMode, + AppLocalizations.of(context)!.gymMode, style: TextStyle(color: Colors.white), ), Icon( @@ -273,7 +271,7 @@ class DayHeaderDismissible extends StatelessWidget { content: Text('Would open weight log form for this day'), actions: [ TextButton( - child: Text(AppLocalizations.of(context).dismiss), + child: Text(AppLocalizations.of(context)!.dismiss), onPressed: () => Navigator.of(context).pop(), ), ], diff --git a/lib/widgets/workouts/exercises.dart b/lib/widgets/workouts/exercises.dart index d6940554a..c6758e7cd 100644 --- a/lib/widgets/workouts/exercises.dart +++ b/lib/widgets/workouts/exercises.dart @@ -20,10 +20,9 @@ import 'package:flutter/material.dart'; class ExerciseImage extends StatelessWidget { const ExerciseImage({ - Key key, - @required this.imageUrl, - @required this.serverUrl, - }) : super(key: key); + required this.imageUrl, + required this.serverUrl, + }); final String imageUrl; final String serverUrl; diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index 44c5143ed..7853dc856 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -37,46 +37,43 @@ class WorkoutForm extends StatelessWidget { WorkoutPlan _plan; final _form = GlobalKey(); - WorkoutForm( - this._plan, { - Key key, - }) : super(key: key); + WorkoutForm(this._plan); final TextEditingController workoutController = TextEditingController(); @override Widget build(BuildContext context) { - workoutController.text = _plan.description ?? ''; + workoutController.text = _plan.description; return Form( key: _form, child: Column( children: [ TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).description), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.description), controller: workoutController, validator: (value) { const minLength = 5; const maxLength = 100; - if (value.isEmpty || value.length < minLength || value.length > maxLength) { + if (value!.isEmpty || value.length < minLength || value.length > maxLength) { return 'Please enter between $minLength and $maxLength characters.'; } return null; }, onFieldSubmitted: (_) {}, onSaved: (newValue) { - _plan.description = newValue; + _plan.description = newValue!; }, ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { // Validate and save - final isValid = _form.currentState.validate(); + final isValid = _form.currentState!.validate(); if (!isValid) { return; } - _form.currentState.save(); + _form.currentState!.save(); // Save to DB final workout = _plan.id != null @@ -112,9 +109,9 @@ class _DayCheckboxState extends State { return CheckboxListTile( title: Text(widget._day.getDayName(widget._dayNr)), value: _isSelected, - onChanged: (bool newValue) { + onChanged: (bool? newValue) { setState(() { - _isSelected = newValue; + _isSelected = newValue!; if (!newValue) { widget._day.daysOfWeek.remove(widget._dayNr); } else { @@ -129,15 +126,11 @@ class _DayCheckboxState extends State { class DayFormWidget extends StatefulWidget { final WorkoutPlan workout; final dayController = TextEditingController(); - Day _day; + Day _day = Day(); - DayFormWidget({ - @required this.workout, - day, - }) { + DayFormWidget(this.workout, [Day? day]) { this._day = day ?? Day(); - _day.workout = this.workout; - _day.workoutId = this.workout.id; + _day.workoutId = this.workout.id!; } @override @@ -156,15 +149,15 @@ class _DayFormWidgetState extends State { child: Column( children: [ TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).description), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.description), controller: widget.dayController, onSaved: (value) { - widget._day.description = value; + widget._day.description = value!; }, validator: (value) { const minLength = 5; const maxLength = 100; - if (value.isEmpty || value.length < minLength || value.length > maxLength) { + if (value!.isEmpty || value.length < minLength || value.length > maxLength) { return 'Please enter between $minLength and $maxLength characters.'; } return null; @@ -174,12 +167,12 @@ class _DayFormWidgetState extends State { Text('Week days'), ...Day.weekdays.keys.map((dayNr) => DayCheckbox(dayNr, widget._day)).toList(), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { - if (!_form.currentState.validate()) { + if (!_form.currentState!.validate()) { return; } - _form.currentState.save(); + _form.currentState!.save(); try { Provider.of(context, listen: false).addDay( @@ -217,11 +210,11 @@ class _DayFormWidgetState extends State { class SetFormWidget extends StatefulWidget { Day _day; - Set _set; + Set _set = Set(); - SetFormWidget(Day day, [Set set]) { - this._day = day; - this._set = set ?? Set(day: day.id, sets: 4); + SetFormWidget(Day this._day, [Set? set]) { + //this._day = day; + this._set = set ?? Set.withData(day: _day.id, sets: 4); } @override @@ -261,7 +254,7 @@ class _SetFormWidgetState extends State { textFieldConfiguration: TextFieldConfiguration( controller: this._exercisesController, decoration: InputDecoration( - labelText: AppLocalizations.of(context).exercise, + labelText: AppLocalizations.of(context)!.exercise, helperMaxLines: 3, helperText: 'You can search for more than one exercise, they will be grouped ' 'together for a superset.'), @@ -270,35 +263,36 @@ class _SetFormWidgetState extends State { return await Provider.of(context, listen: false).searchExercise(pattern); }, itemBuilder: (context, suggestion) { - // TODO: this won't work if the server uses e.g. AWS to serve - // the static files - String serverUrl = Provider.of(context, listen: false).serverUrl; - final exercise = Provider.of(context, listen: false) - .findById(suggestion['data']['id']); + final result = suggestion! as Map; + + String serverUrl = Provider.of(context, listen: false).serverUrl!; + final exercise = + Provider.of(context, listen: false).findById(result['data']['id']); return ListTile( leading: Container( width: 45, - child: suggestion['data']['image'] != null + child: result['data']['image'] != null ? ExerciseImage( - imageUrl: suggestion['data']['image'], + imageUrl: result['data']['image'], serverUrl: serverUrl, ) : Container(), ), title: Text(exercise.name), - subtitle: Text(exercise.category.name), + subtitle: Text(exercise.categoryObj.name), ); }, transitionBuilder: (context, suggestionsBox, controller) { return suggestionsBox; }, onSuggestionSelected: (suggestion) { - final exercise = Provider.of(context, listen: false) - .findById(suggestion['data']['id']); + final result = suggestion! as Map; + final exercise = + Provider.of(context, listen: false).findById(result['data']['id']); addExercise(exercise); }, validator: (value) { - if (value.isEmpty) { + if (value!.isEmpty) { return 'Please select an exercise'; } return null; @@ -320,7 +314,9 @@ class _SetFormWidgetState extends State { widget._set.settings = []; for (var exercise in widget._set.exercisesObj) { for (int loop = 0; loop < widget._set.sets; loop++) { - widget._set.settings.add(Setting(exerciseObj: exercise)); + Setting setting = Setting(); + setting.exerciseObj = exercise; + widget._set.settings.add(setting); } } @@ -360,13 +356,13 @@ class _SetFormWidgetState extends State { ), ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { - final isValid = _formKey.currentState.validate(); + final isValid = _formKey.currentState!.validate(); if (!isValid) { return; } - _formKey.currentState.save(); + _formKey.currentState!.save(); final workoutProvider = Provider.of(context, listen: false); @@ -379,11 +375,12 @@ class _SetFormWidgetState extends State { // Save remaining settings for (var setting in widget._set.settings) { - setting.setId = setDb.id; + setting.setId = setDb.id!; - setting.weightUnit = setting.weightUnit ?? workoutProvider.defaultWeightUnit.id; - setting.repetitionUnit = - setting.repetitionUnit ?? workoutProvider.defaultRepetitionUnit.id; + setting.weightUnitId = workoutProvider.defaultWeightUnit.id; + //setting.weightUnitId ?? workoutProvider.defaultWeightUnit.id; + setting.repetitionUnitId = workoutProvider.defaultRepetitionUnit.id; + //setting.repetitionUnitId ?? workoutProvider.defaultRepetitionUnit.id; setting.comment = ''; setting.repsText = 'temp text'; @@ -406,18 +403,19 @@ class _SetFormWidgetState extends State { class ExerciseSetting extends StatelessWidget { Exercise _exercise; - int _numberOfSets; + int _numberOfSets = 4; bool _detailed; Function removeExercise; List _settings = []; - ExerciseSetting(Exercise exercise, List settings, bool expanded, double sliderValue, - removeExercise) { - this._exercise = exercise; - this._settings = settings; - this._detailed = expanded; + ExerciseSetting( + this._exercise, + this._settings, + this._detailed, + double sliderValue, + this.removeExercise, + ) { this._numberOfSets = sliderValue.round(); - this.removeExercise = removeExercise; } Widget getRow() { @@ -478,9 +476,7 @@ class RepsInputWidget extends StatelessWidget { final _repsController = TextEditingController(); Setting _setting; - RepsInputWidget(Setting setting) { - this._setting = setting; - } + RepsInputWidget(this._setting); @override Widget build(BuildContext context) { @@ -503,9 +499,7 @@ class WeightInputWidget extends StatelessWidget { final _weightController = TextEditingController(); Setting _setting; - WeightInputWidget(Setting setting) { - this._setting = setting; - } + WeightInputWidget(this._setting); @override Widget build(BuildContext context) { @@ -525,7 +519,7 @@ class WeightInputWidget extends StatelessWidget { } class RiRInputWidget extends StatefulWidget { - RiRInputWidget({Key key}) : super(key: key); + RiRInputWidget(); @override _RiRInputWidgetState createState() => _RiRInputWidgetState(); @@ -542,9 +536,9 @@ class _RiRInputWidgetState extends State { height: 0, //color: Colors.deepPurpleAccent, ), - onChanged: (String newValue) { + onChanged: (String? newValue) { setState(() { - dropdownValue = newValue; + dropdownValue = newValue!; }); }, items: ['1', '1.5', '2', '2.5', '3', '3.5'] @@ -559,14 +553,14 @@ class _RiRInputWidgetState extends State { } class WeightUnitInputWidget extends StatefulWidget { - WeightUnitInputWidget({Key key}) : super(key: key); + WeightUnitInputWidget({Key? key}) : super(key: key); @override _WeightUnitInputWidgetState createState() => _WeightUnitInputWidgetState(); } class _WeightUnitInputWidgetState extends State { - WeightUnit dropdownValue; + late WeightUnit dropdownValue; @override Widget build(BuildContext context) { @@ -576,9 +570,9 @@ class _WeightUnitInputWidgetState extends State { height: 0, // color: Colors.deepPurpleAccent, ), - onChanged: (WeightUnit newValue) { + onChanged: (WeightUnit? newValue) { setState(() { - dropdownValue = newValue; + dropdownValue = newValue!; }); }, items: Provider.of(context, listen: false) @@ -597,14 +591,14 @@ class _WeightUnitInputWidgetState extends State { } class RepetitionUnitInputWidget extends StatefulWidget { - RepetitionUnitInputWidget({Key key}) : super(key: key); + RepetitionUnitInputWidget(); @override _RepetitionUnitInputWidgetState createState() => _RepetitionUnitInputWidgetState(); } class _RepetitionUnitInputWidgetState extends State { - RepetitionUnit dropdownValue; + late RepetitionUnit dropdownValue; @override Widget build(BuildContext context) { @@ -614,9 +608,9 @@ class _RepetitionUnitInputWidgetState extends State { height: 0, // color: Colors.deepPurpleAccent, ), - onChanged: (RepetitionUnit newValue) { + onChanged: (RepetitionUnit? newValue) { setState(() { - dropdownValue = newValue; + dropdownValue = newValue!; }); }, items: Provider.of(context, listen: false) diff --git a/lib/widgets/workouts/gym_mode.dart b/lib/widgets/workouts/gym_mode.dart index 8a9b37def..959c7082d 100644 --- a/lib/widgets/workouts/gym_mode.dart +++ b/lib/widgets/workouts/gym_mode.dart @@ -104,7 +104,7 @@ class StartPage extends StatelessWidget { Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: Text( - AppLocalizations.of(context).todaysWorkout, + AppLocalizations.of(context)!.todaysWorkout, style: Theme.of(context).textTheme.headline5, ), ), @@ -165,7 +165,7 @@ class LogPage extends StatelessWidget { _log.date = DateTime.now(); _log.exercise = _exercise.id; - _log.workoutPlan = _workoutPlan.id; + _log.workoutPlan = _workoutPlan.id!; _log.repetitionUnit = 1; _log.weightUnit = 1; } @@ -191,33 +191,33 @@ class LogPage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).repetitions), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.repetitions), controller: _repsController, keyboardType: TextInputType.number, onFieldSubmitted: (_) {}, onSaved: (newValue) { - _log.reps = int.parse(newValue); + _log.reps = int.parse(newValue!); }, validator: (value) { try { - double.parse(value); + double.parse(value!); } catch (error) { - return AppLocalizations.of(context).enterValidNumber; + return AppLocalizations.of(context)!.enterValidNumber; } return null; }, ), TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).weight), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.weight), controller: _weightController, keyboardType: TextInputType.number, onFieldSubmitted: (_) {}, onSaved: (newValue) { - _log.weight = double.parse(newValue); + _log.weight = double.parse(newValue!); }, ), TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).rir), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.rir), controller: _rirController, keyboardType: TextInputType.number, onFieldSubmitted: (_) {}, @@ -225,7 +225,7 @@ class LogPage extends StatelessWidget { ), /* TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).comment), + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.comment), controller: _commentController, keyboardType: TextInputType.multiline, maxLines: 3, @@ -237,14 +237,14 @@ class LogPage extends StatelessWidget { */ ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { // Validate and save the current values to the weightEntry - final isValid = _form.currentState.validate(); + final isValid = _form.currentState!.validate(); if (!isValid) { return; } - _form.currentState.save(); + _form.currentState!.save(); // Save the entry on the server try { @@ -345,15 +345,15 @@ class _SessionPageState extends State { builder: (FormFieldState state) { return InputDecorator( decoration: InputDecoration( - labelText: AppLocalizations.of(context).impression, + labelText: AppLocalizations.of(context)!.impression, ), child: DropdownButtonHideUnderline( child: DropdownButton( value: impressionValue, isDense: true, - onChanged: (int newValue) { + onChanged: (int? newValue) { setState(() { - impressionValue = newValue; + impressionValue = newValue!; state.didChange(newValue); }); }, @@ -361,7 +361,7 @@ class _SessionPageState extends State { return DropdownMenuItem( value: key, child: Text( - ImpressionMap[key], + ImpressionMap[key]!, ), ); }).toList(), @@ -372,14 +372,14 @@ class _SessionPageState extends State { ), TextFormField( decoration: InputDecoration( - labelText: AppLocalizations.of(context).notes, + labelText: AppLocalizations.of(context)!.notes, ), maxLines: 3, controller: notesController, keyboardType: TextInputType.multiline, onFieldSubmitted: (_) {}, onSaved: (newValue) { - _session.notes = newValue; + _session.notes = newValue!; }, ), Row( @@ -387,7 +387,7 @@ class _SessionPageState extends State { Flexible( child: TextFormField( decoration: - InputDecoration(labelText: AppLocalizations.of(context).timeStart), + InputDecoration(labelText: AppLocalizations.of(context)!.timeStart), controller: timeStartController, onFieldSubmitted: (_) {}, onSaved: (newValue) {}, @@ -396,7 +396,7 @@ class _SessionPageState extends State { Flexible( child: TextFormField( decoration: - InputDecoration(labelText: AppLocalizations.of(context).timeEnd), + InputDecoration(labelText: AppLocalizations.of(context)!.timeEnd), controller: timeEndController, onFieldSubmitted: (_) {}, onSaved: (newValue) {}, @@ -405,21 +405,20 @@ class _SessionPageState extends State { ], ), ElevatedButton( - child: Text(AppLocalizations.of(context).save), + child: Text(AppLocalizations.of(context)!.save), onPressed: () async { // Validate and save the current values to the weightEntry - final isValid = _form.currentState.validate(); + final isValid = _form.currentState!.validate(); if (!isValid) { return; } - _form.currentState.save(); + _form.currentState!.save(); _session.date = DateTime.now(); - _session.workoutId = widget._workoutPlan.id; + _session.workoutId = widget._workoutPlan.id!; _session.impression = impressionValue; // Save the entry on the server try { - print(_session.toJson()); await Provider.of(context, listen: false).addSession(_session); Navigator.of(context).pop(); } on WgerHttpException catch (error) { @@ -456,7 +455,7 @@ class TimerWidget extends StatefulWidget { class _TimerWidgetState extends State { // See https://stackoverflow.com/questions/54610121/flutter-countdown-timer - Timer _timer; + Timer? _timer; int _seconds = 1; final _maxSeconds = 600; DateTime today = new DateTime(2000, 1, 1, 0, 0, 0); diff --git a/lib/widgets/workouts/log.dart b/lib/widgets/workouts/log.dart index 3716f41a5..b5dcacad7 100644 --- a/lib/widgets/workouts/log.dart +++ b/lib/widgets/workouts/log.dart @@ -36,8 +36,8 @@ class ExerciseLog extends StatelessWidget { final _workoutPlansData = Provider.of(context, listen: false); final _workout = _workoutPlansData.currentPlan; - Future _getChartEntries(BuildContext context) async { - return await _workoutPlansData.fetchLogData(_workout, _exercise); + Future> _getChartEntries(BuildContext context) async { + return await _workoutPlansData.fetchLogData(_workout!, _exercise); } return Column( @@ -48,54 +48,55 @@ class ExerciseLog extends StatelessWidget { ), FutureBuilder( future: _getChartEntries(context), - builder: (context, snapshot) => snapshot.connectionState == ConnectionState.waiting - ? Container( - height: 120, - child: Center(child: CircularProgressIndicator()), - ) - : Column( - children: [ - Container( + builder: (context, AsyncSnapshot> snapshot) => + snapshot.connectionState == ConnectionState.waiting + ? Container( height: 120, - child: LogChartWidget(snapshot.data), - ), - const Padding(padding: EdgeInsets.symmetric(vertical: 5)), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - ...snapshot.data['logs'].entries.map((e) { - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 10), - child: Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text( - '${DateFormat.yMd().format(DateTime.parse(e.key))}', - style: TextStyle(fontWeight: FontWeight.bold), + child: Center(child: CircularProgressIndicator()), + ) + : Column( + children: [ + Container( + height: 120, + child: LogChartWidget(snapshot.data), + ), + const Padding(padding: EdgeInsets.symmetric(vertical: 5)), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + ...snapshot.data!['logs']!.entries.map((e) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + '${DateFormat.yMd().format(DateTime.parse(e.key))}', + style: TextStyle(fontWeight: FontWeight.bold), + ), + ...e.value.map((i) { + return Text("${i['weight']} - ${i['reps']}"); + }) + ], ), - ...e.value.map((i) { - return Text("${i['weight']} - ${i['reps']}"); - }) - ], - ), - ); - }).toList(), - ], - ), + ); + }).toList(), + ], + ), + ), + ], ), - ], - ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - Text(AppLocalizations.of(context).amount), - Text(AppLocalizations.of(context).unit), - Text(AppLocalizations.of(context).weight), - Text(AppLocalizations.of(context).unit), - Text(AppLocalizations.of(context).rir), + Text(AppLocalizations.of(context)!.amount), + Text(AppLocalizations.of(context)!.unit), + Text(AppLocalizations.of(context)!.weight), + Text(AppLocalizations.of(context)!.unit), + Text(AppLocalizations.of(context)!.rir), ], ), ], diff --git a/lib/widgets/workouts/workout_logs.dart b/lib/widgets/workouts/workout_logs.dart index 4ab710312..bef110723 100644 --- a/lib/widgets/workouts/workout_logs.dart +++ b/lib/widgets/workouts/workout_logs.dart @@ -61,14 +61,14 @@ class _WorkoutLogsState extends State { Padding( padding: const EdgeInsets.all(8.0), child: Text( - AppLocalizations.of(context).logHelpEntries, + AppLocalizations.of(context)!.logHelpEntries, textAlign: TextAlign.justify, ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( - AppLocalizations.of(context).logHelpEntriesUnits, + AppLocalizations.of(context)!.logHelpEntriesUnits, textAlign: TextAlign.justify, ), ), diff --git a/lib/widgets/workouts/workout_plan_detail.dart b/lib/widgets/workouts/workout_plan_detail.dart index 5e864cf7a..19abce7cd 100644 --- a/lib/widgets/workouts/workout_plan_detail.dart +++ b/lib/widgets/workouts/workout_plan_detail.dart @@ -57,12 +57,12 @@ class _WorkoutPlanDetailState extends State { Column( children: [ ElevatedButton( - child: Text(AppLocalizations.of(context).add), + child: Text(AppLocalizations.of(context)!.add), onPressed: () { showFormBottomSheet( context, - AppLocalizations.of(context).newDay, - DayFormWidget(workout: widget._workoutPlan), + AppLocalizations.of(context)!.newDay, + DayFormWidget(widget._workoutPlan), scrollControlled: true, ); }, diff --git a/lib/widgets/workouts/workout_plans_list.dart b/lib/widgets/workouts/workout_plans_list.dart index 160e720d1..2a2ed6c99 100644 --- a/lib/widgets/workouts/workout_plans_list.dart +++ b/lib/widgets/workouts/workout_plans_list.dart @@ -44,22 +44,22 @@ class WorkoutPlansList extends StatelessWidget { builder: (BuildContext contextDialog) { return AlertDialog( content: Text( - AppLocalizations.of(context).confirmDelete(currentWorkout.description), + AppLocalizations.of(context)!.confirmDelete(currentWorkout.description), ), actions: [ TextButton( - child: Text(AppLocalizations.of(context).cancel), + child: Text(AppLocalizations.of(context)!.cancel), onPressed: () => Navigator.of(contextDialog).pop(), ), TextButton( child: Text( - AppLocalizations.of(context).delete, + AppLocalizations.of(context)!.delete, style: TextStyle(color: Theme.of(context).errorColor), ), onPressed: () { // Confirmed, delete the workout Provider.of(context, listen: false) - .deleteWorkout(currentWorkout.id); + .deleteWorkout(currentWorkout.id!); // Close the popup Navigator.of(contextDialog).pop(); @@ -68,7 +68,7 @@ class WorkoutPlansList extends StatelessWidget { Scaffold.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context)!.successfullyDeleted, textAlign: TextAlign.center, ), ), @@ -97,9 +97,9 @@ class WorkoutPlansList extends StatelessWidget { child: Card( child: ListTile( onTap: () { - _workoutProvider.setCurrentPlan(currentWorkout.id); + _workoutProvider.setCurrentPlan(currentWorkout.id!); - return Navigator.of(context) + Navigator.of(context) .pushNamed(WorkoutPlanScreen.routeName, arguments: currentWorkout); }, title: Text(currentWorkout.description), diff --git a/pubspec.lock b/pubspec.lock index 38948fafb..9b3b172be 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,14 +7,14 @@ packages: name: _fe_analyzer_shared url: "https://pub.dartlang.org" source: hosted - version: "18.0.0" + version: "19.0.0" analyzer: dependency: transitive description: name: analyzer url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "1.3.0" android_metadata: dependency: "direct main" description: @@ -105,7 +105,7 @@ packages: name: built_value url: "https://pub.dartlang.org" source: hosted - version: "8.0.3" + version: "8.0.4" characters: dependency: transitive description: @@ -163,7 +163,7 @@ packages: source: hosted version: "3.7.0" collection: - dependency: transitive + dependency: "direct main" description: name: collection url: "https://pub.dartlang.org" @@ -236,28 +236,28 @@ packages: name: flutter_calendar_carousel url: "https://pub.dartlang.org" source: hosted - version: "1.5.3" + version: "2.0.0" flutter_keyboard_visibility: dependency: transitive description: name: flutter_keyboard_visibility url: "https://pub.dartlang.org" source: hosted - version: "4.0.6" + version: "5.0.0" flutter_keyboard_visibility_platform_interface: dependency: transitive description: name: flutter_keyboard_visibility_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.1" + version: "2.0.0" flutter_keyboard_visibility_web: dependency: transitive description: name: flutter_keyboard_visibility_web url: "https://pub.dartlang.org" source: hosted - version: "1.0.1" + version: "2.0.0" flutter_launcher_icons: dependency: "direct dev" description: @@ -281,7 +281,7 @@ packages: name: flutter_typeahead url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "3.1.0" flutter_web_plugins: dependency: transitive description: flutter @@ -293,7 +293,7 @@ packages: name: glob url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "2.0.1" graphs: dependency: transitive description: @@ -307,7 +307,7 @@ packages: name: http url: "https://pub.dartlang.org" source: hosted - version: "0.13.0" + version: "0.13.1" http_multi_server: dependency: transitive description: @@ -328,7 +328,7 @@ packages: name: image url: "https://pub.dartlang.org" source: hosted - version: "3.0.1" + version: "3.0.2" intl: dependency: "direct main" description: @@ -356,7 +356,7 @@ packages: name: json_annotation url: "https://pub.dartlang.org" source: hosted - version: "4.0.0" + version: "4.0.1" json_serializable: dependency: "direct dev" description: @@ -440,7 +440,7 @@ packages: name: path_provider_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "2.0.1" path_provider_windows: dependency: transitive description: @@ -475,7 +475,7 @@ packages: name: plugin_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "2.0.0" pool: dependency: transitive description: @@ -489,7 +489,7 @@ packages: name: process url: "https://pub.dartlang.org" source: hosted - version: "4.1.0" + version: "4.2.1" provider: dependency: "direct main" description: @@ -683,7 +683,7 @@ packages: name: url_launcher_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.0.1" + version: "2.0.2" url_launcher_web: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index c16ac2e01..0c8d894cf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -18,7 +18,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 0.1.0+7 environment: - sdk: ">=2.10.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: @@ -30,15 +30,16 @@ dependencies: intl: ^0.17.0 http: ^0.13.0 shared_preferences: ^2.0.5 - flutter_calendar_carousel: ^1.5.3 + flutter_calendar_carousel: ^2.0.0 cupertino_icons: ^1.0.0 json_annotation: ^4.0.0 url_launcher: ^6.0.2 charts_flutter: ^0.10.0 - flutter_typeahead: ^2.0.0 + flutter_typeahead: ^3.1.0 table_calendar: ^2.3.3 package_info: ^2.0.0 android_metadata: ^0.1.3 + collection: ^1.15.0-nullsafety.4 dev_dependencies: flutter_test: diff --git a/test/weight_model_test.dart b/test/weight_model_test.dart index 6e17a1682..d3ff463e3 100644 --- a/test/weight_model_test.dart +++ b/test/weight_model_test.dart @@ -45,7 +45,7 @@ void main() { group('model', () { test('Test the individual values from the model', () { WeightEntry _weightModel; - _weightModel = WeightEntry(); + //_weightModel = WeightEntry(); _weightModel = WeightEntry(id: 1, weight: 80, date: DateTime(2020, 10, 01)); expect(_weightModel.id, 1); diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart index b24362885..b943b4e2f 100644 --- a/test/weight_screen_test.dart +++ b/test/weight_screen_test.dart @@ -34,11 +34,11 @@ void main() { Widget createHomeScreen({locale = 'en'}) { final client = MockClient(); when(client.delete( - any, + any!, headers: anyNamed('headers'), )).thenAnswer((_) async => http.Response('', 200)); when(client.post( - any, + any!, headers: anyNamed('headers'), body: anyNamed('body'), )).thenAnswer( From 5263c074f273f1ea1ad8939958a73020c3818c52 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 30 Mar 2021 12:51:18 +0200 Subject: [PATCH 46/58] Make tests work with (no sound) null safety --- .github/workflows/ci.yml | 5 +- lib/models/body_weight/weight_entry.g.dart | 2 +- lib/models/nutrition/meal_item.g.dart | 4 +- pubspec.lock | 12 +-- test/utils.dart | 4 - test/weight_provider_test.dart | 3 + test/weight_provider_test.mocks.dart | 98 ++++++++++++++++++++++ test/weight_screen_test.dart | 7 +- test/weight_screen_test.mocks.dart | 98 ++++++++++++++++++++++ 9 files changed, 216 insertions(+), 17 deletions(-) create mode 100644 test/weight_provider_test.mocks.dart create mode 100644 test/weight_screen_test.mocks.dart diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1c82779b..4e54efabd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,8 +25,9 @@ jobs: run: flutter gen-l10n - name: Test app - run: flutter test --coverage - + run: flutter test --no-sound-null-safety --coverage + #run: flutter test --coverage + #- name: Upload coverage to Codecov # uses: codecov/codecov-action@v1 # with: diff --git a/lib/models/body_weight/weight_entry.g.dart b/lib/models/body_weight/weight_entry.g.dart index 4113a23e2..59ae955d4 100644 --- a/lib/models/body_weight/weight_entry.g.dart +++ b/lib/models/body_weight/weight_entry.g.dart @@ -11,7 +11,7 @@ WeightEntry _$WeightEntryFromJson(Map json) { return WeightEntry( id: json['id'] as int?, weight: toNum(json['weight'] as String?), - date: DateTime.parse(json['date'] as String), + date: json['date'] == null ? null : DateTime.parse(json['date'] as String), ); } diff --git a/lib/models/nutrition/meal_item.g.dart b/lib/models/nutrition/meal_item.g.dart index 1ca8bd374..a1ab46fa9 100644 --- a/lib/models/nutrition/meal_item.g.dart +++ b/lib/models/nutrition/meal_item.g.dart @@ -10,8 +10,8 @@ MealItem _$MealItemFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'amount']); return MealItem( id: json['id'] as int?, - meal: json['meal'] as int, - ingredientId: json['ingredient'] as int, + meal: json['meal'] as int?, + ingredientId: json['ingredient'], weightUnit: json['weight_unit'] == null ? null : IngredientWeightUnit.fromJson( diff --git a/pubspec.lock b/pubspec.lock index 9b3b172be..4fee1ffc1 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -196,7 +196,7 @@ packages: name: dart_style url: "https://pub.dartlang.org" source: hosted - version: "1.3.14" + version: "2.0.0" fake_async: dependency: transitive description: @@ -363,14 +363,14 @@ packages: name: json_serializable url: "https://pub.dartlang.org" source: hosted - version: "4.0.3" + version: "4.1.0" logging: dependency: transitive description: name: logging url: "https://pub.dartlang.org" source: hosted - version: "1.0.0" + version: "1.0.1" matcher: dependency: transitive description: @@ -398,7 +398,7 @@ packages: name: mockito url: "https://pub.dartlang.org" source: hosted - version: "5.0.2" + version: "5.0.3" nested: dependency: transitive description: @@ -585,7 +585,7 @@ packages: name: source_gen url: "https://pub.dartlang.org" source: hosted - version: "0.9.10+4" + version: "1.0.0" source_span: dependency: transitive description: @@ -662,7 +662,7 @@ packages: name: url_launcher url: "https://pub.dartlang.org" source: hosted - version: "6.0.2" + version: "6.0.3" url_launcher_linux: dependency: transitive description: diff --git a/test/utils.dart b/test/utils.dart index bc8cd5a9d..8b068d32c 100644 --- a/test/utils.dart +++ b/test/utils.dart @@ -16,12 +16,8 @@ * along with this program. If not, see . */ -import 'package:http/http.dart' as http; -import 'package:mockito/mockito.dart'; import 'package:wger/providers/auth.dart'; -class MockClient extends Mock implements http.Client {} - // Test Auth provider final Auth testAuth = Auth() ..token = 'FooBar' diff --git a/test/weight_provider_test.dart b/test/weight_provider_test.dart index ea8900503..e238a88d8 100644 --- a/test/weight_provider_test.dart +++ b/test/weight_provider_test.dart @@ -20,12 +20,15 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; +import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/body_weight.dart'; import 'utils.dart'; +import 'weight_provider_test.mocks.dart'; +@GenerateMocks([http.Client]) void main() { group('test body weight provider', () { test('Test that the weight entries are correctly loaded', () async { diff --git a/test/weight_provider_test.mocks.dart b/test/weight_provider_test.mocks.dart new file mode 100644 index 000000000..5921f2030 --- /dev/null +++ b/test/weight_provider_test.mocks.dart @@ -0,0 +1,98 @@ +// Mocks generated by Mockito 5.0.3 from annotations +// in wger/test/weight_provider_test.dart. +// Do not manually edit this file. + +import 'dart:async' as _i6; +import 'dart:convert' as _i7; +import 'dart:typed_data' as _i3; + +import 'package:http/src/base_request.dart' as _i8; +import 'package:http/src/client.dart' as _i5; +import 'package:http/src/response.dart' as _i2; +import 'package:http/src/streamed_response.dart' as _i4; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: comment_references +// ignore_for_file: unnecessary_parenthesis + +class _FakeResponse extends _i1.Fake implements _i2.Response {} + +class _FakeUint8List extends _i1.Fake implements _i3.Uint8List {} + +class _FakeStreamedResponse extends _i1.Fake implements _i4.StreamedResponse {} + +/// A class which mocks [Client]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockClient extends _i1.Mock implements _i5.Client { + MockClient() { + _i1.throwOnMissingStub(this); + } + + @override + _i6.Future<_i2.Response> head(Uri? url, {Map? headers}) => + (super.noSuchMethod(Invocation.method(#head, [url], {#headers: headers}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> get(Uri? url, {Map? headers}) => + (super.noSuchMethod(Invocation.method(#get, [url], {#headers: headers}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> post(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#post, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> put(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#put, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> patch(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#patch, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> delete(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#delete, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future read(Uri? url, {Map? headers}) => + (super.noSuchMethod(Invocation.method(#read, [url], {#headers: headers}), + returnValue: Future.value('')) as _i6.Future); + @override + _i6.Future<_i3.Uint8List> readBytes(Uri? url, + {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: Future.value(_FakeUint8List())) + as _i6.Future<_i3.Uint8List>); + @override + _i6.Future<_i4.StreamedResponse> send(_i8.BaseRequest? request) => + (super.noSuchMethod(Invocation.method(#send, [request]), + returnValue: Future.value(_FakeStreamedResponse())) + as _i6.Future<_i4.StreamedResponse>); +} diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart index b943b4e2f..6299462c7 100644 --- a/test/weight_screen_test.dart +++ b/test/weight_screen_test.dart @@ -20,6 +20,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; +import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; @@ -29,16 +30,18 @@ import 'package:wger/widgets/weight/charts.dart'; import 'package:wger/widgets/weight/forms.dart'; import 'utils.dart'; +import 'weight_screen_test.mocks.dart'; +@GenerateMocks([http.Client]) void main() { Widget createHomeScreen({locale = 'en'}) { final client = MockClient(); when(client.delete( - any!, + any, headers: anyNamed('headers'), )).thenAnswer((_) async => http.Response('', 200)); when(client.post( - any!, + any, headers: anyNamed('headers'), body: anyNamed('body'), )).thenAnswer( diff --git a/test/weight_screen_test.mocks.dart b/test/weight_screen_test.mocks.dart new file mode 100644 index 000000000..fa03a0534 --- /dev/null +++ b/test/weight_screen_test.mocks.dart @@ -0,0 +1,98 @@ +// Mocks generated by Mockito 5.0.3 from annotations +// in wger/test/weight_screen_test.dart. +// Do not manually edit this file. + +import 'dart:async' as _i6; +import 'dart:convert' as _i7; +import 'dart:typed_data' as _i3; + +import 'package:http/src/base_request.dart' as _i8; +import 'package:http/src/client.dart' as _i5; +import 'package:http/src/response.dart' as _i2; +import 'package:http/src/streamed_response.dart' as _i4; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: comment_references +// ignore_for_file: unnecessary_parenthesis + +class _FakeResponse extends _i1.Fake implements _i2.Response {} + +class _FakeUint8List extends _i1.Fake implements _i3.Uint8List {} + +class _FakeStreamedResponse extends _i1.Fake implements _i4.StreamedResponse {} + +/// A class which mocks [Client]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockClient extends _i1.Mock implements _i5.Client { + MockClient() { + _i1.throwOnMissingStub(this); + } + + @override + _i6.Future<_i2.Response> head(Uri? url, {Map? headers}) => + (super.noSuchMethod(Invocation.method(#head, [url], {#headers: headers}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> get(Uri? url, {Map? headers}) => + (super.noSuchMethod(Invocation.method(#get, [url], {#headers: headers}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> post(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#post, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> put(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#put, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> patch(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#patch, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future<_i2.Response> delete(Uri? url, + {Map? headers, + Object? body, + _i7.Encoding? encoding}) => + (super.noSuchMethod( + Invocation.method(#delete, [url], + {#headers: headers, #body: body, #encoding: encoding}), + returnValue: Future.value(_FakeResponse())) + as _i6.Future<_i2.Response>); + @override + _i6.Future read(Uri? url, {Map? headers}) => + (super.noSuchMethod(Invocation.method(#read, [url], {#headers: headers}), + returnValue: Future.value('')) as _i6.Future); + @override + _i6.Future<_i3.Uint8List> readBytes(Uri? url, + {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: Future.value(_FakeUint8List())) + as _i6.Future<_i3.Uint8List>); + @override + _i6.Future<_i4.StreamedResponse> send(_i8.BaseRequest? request) => + (super.noSuchMethod(Invocation.method(#send, [request]), + returnValue: Future.value(_FakeStreamedResponse())) + as _i6.Future<_i4.StreamedResponse>); +} From 11c8485d2e66f1ccccd5956914888a10ba360c9f Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 30 Mar 2021 12:52:01 +0200 Subject: [PATCH 47/58] Target Android SDK version 30 --- android/app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index ad105f027..712fed186 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -69,7 +69,7 @@ android { // Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "de.wger.flutter" minSdkVersion 16 - targetSdkVersion 29 + targetSdkVersion 30 versionCode flutterVersionCode.toInteger() versionName flutterVersionName manifestPlaceholders = [WGER_API_KEY: wgerApiKey] From 6b20a635b1d89775af499b45e66047dfca6eb395 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 30 Mar 2021 12:55:04 +0200 Subject: [PATCH 48/58] We still need to run everything with --no-sound-null-safety --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8b7e38239..b9ed36e41 100644 --- a/README.md +++ b/README.md @@ -36,9 +36,11 @@ Generate translation files with ``flutter gen-l10n`` ### 5 -Start the application with ``flutter run`` or use your IDE (please note that -depending on how you run your emulator you will need to change the IP address -of the server) +Start the application with ``flutter run --no-sound-null-safety`` or use your IDE +(please note that depending on how you run your emulator you will need to change the +IP address of the server) + +You can run the tests with ``flutter test --no-sound-null-safety`` ## Translation The application can be easily translated online with [Weblate](https://hosted.weblate.org/engage/wger/). From 97829e0408e510db1d756467bc6b1508f6b7915a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 30 Mar 2021 13:25:36 +0200 Subject: [PATCH 49/58] Add more tests for nutrition and workout plan overview --- lib/widgets/workouts/forms.dart | 4 +- test/base_provider_test.dart | 3 + ...cks.dart => base_provider_test.mocks.dart} | 2 +- test/nutritional_plans_screen_test.dart | 105 +++++++++++++++++ test/weight_provider_test.dart | 2 +- test/weight_provider_test.mocks.dart | 98 ---------------- test/weight_screen_test.dart | 4 +- test/workout_plans_screen_test.dart | 106 ++++++++++++++++++ 8 files changed, 220 insertions(+), 104 deletions(-) rename test/{weight_screen_test.mocks.dart => base_provider_test.mocks.dart} (98%) create mode 100644 test/nutritional_plans_screen_test.dart delete mode 100644 test/weight_provider_test.mocks.dart create mode 100644 test/workout_plans_screen_test.dart diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index 7853dc856..db862dd0d 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -43,7 +43,9 @@ class WorkoutForm extends StatelessWidget { @override Widget build(BuildContext context) { - workoutController.text = _plan.description; + if (_plan.id != null) { + workoutController.text = _plan.description; + } return Form( key: _form, diff --git a/test/base_provider_test.dart b/test/base_provider_test.dart index ec3842a55..3184667de 100644 --- a/test/base_provider_test.dart +++ b/test/base_provider_test.dart @@ -17,10 +17,13 @@ */ import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:mockito/annotations.dart'; import 'package:wger/providers/base_provider.dart'; import 'utils.dart'; +@GenerateMocks([http.Client]) void main() { group('test base provider', () { test('Test the makeUrl helper', () async { diff --git a/test/weight_screen_test.mocks.dart b/test/base_provider_test.mocks.dart similarity index 98% rename from test/weight_screen_test.mocks.dart rename to test/base_provider_test.mocks.dart index fa03a0534..bb43da439 100644 --- a/test/weight_screen_test.mocks.dart +++ b/test/base_provider_test.mocks.dart @@ -1,5 +1,5 @@ // Mocks generated by Mockito 5.0.3 from annotations -// in wger/test/weight_screen_test.dart. +// in wger/test/base_provider_test.dart. // Do not manually edit this file. import 'dart:async' as _i6; diff --git a/test/nutritional_plans_screen_test.dart b/test/nutritional_plans_screen_test.dart new file mode 100644 index 000000000..8cc74e1bc --- /dev/null +++ b/test/nutritional_plans_screen_test.dart @@ -0,0 +1,105 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (C) 2020 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * wger Workout Manager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:mockito/mockito.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/models/nutrition/nutritional_plan.dart'; +import 'package:wger/providers/nutrition.dart'; +import 'package:wger/screens/nutritional_plans_screen.dart'; +import 'package:wger/widgets/nutrition/forms.dart'; + +import 'base_provider_test.mocks.dart'; +import 'utils.dart'; + +void main() { + Widget createHomeScreen({locale = 'en'}) { + final client = MockClient(); + when(client.delete( + any, + headers: anyNamed('headers'), + )).thenAnswer((_) async => http.Response('', 200)); + + return ChangeNotifierProvider( + create: (context) => Nutrition( + testAuth, + [ + NutritionalPlan(id: 1, description: 'test plan 1', creationDate: DateTime(2021, 01, 01)), + NutritionalPlan(id: 2, description: 'test plan 2', creationDate: DateTime(2021, 01, 10)), + ], + client, + ), + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: NutritionScreen(), + ), + ); + } + + testWidgets('Test the widgets on the nutritional plans screen', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + //debugDumpApp(); + expect(find.text('Nutritional plans'), findsOneWidget); + expect(find.byType(Dismissible), findsNWidgets(2)); + expect(find.byType(ListTile), findsNWidgets(2)); + }); + + testWidgets('Test deleting an item by dragging the dismissible', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + await tester.drag(find.byKey(Key('1')), Offset(-500.0, 0.0)); + await tester.pumpAndSettle(); + + // Confirmation dialog + expect(find.byType(AlertDialog), findsOneWidget); + + // Confirm + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); + expect(find.byType(ListTile), findsOneWidget); + }); + + testWidgets('Test the form on the nutritional plan screen', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + expect(find.byType(PlanForm), findsNothing); + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + expect(find.byType(PlanForm), findsOneWidget); + }); + + testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + expect(find.text('1/1/2021'), findsOneWidget); + expect(find.text('1/10/2021'), findsOneWidget); + }); + + testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen(locale: 'de')); + + expect(find.text('1.1.2021'), findsOneWidget); + expect(find.text('10.1.2021'), findsOneWidget); + }); +} diff --git a/test/weight_provider_test.dart b/test/weight_provider_test.dart index e238a88d8..b29b78954 100644 --- a/test/weight_provider_test.dart +++ b/test/weight_provider_test.dart @@ -25,8 +25,8 @@ import 'package:mockito/mockito.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/body_weight.dart'; +import 'base_provider_test.mocks.dart'; import 'utils.dart'; -import 'weight_provider_test.mocks.dart'; @GenerateMocks([http.Client]) void main() { diff --git a/test/weight_provider_test.mocks.dart b/test/weight_provider_test.mocks.dart deleted file mode 100644 index 5921f2030..000000000 --- a/test/weight_provider_test.mocks.dart +++ /dev/null @@ -1,98 +0,0 @@ -// Mocks generated by Mockito 5.0.3 from annotations -// in wger/test/weight_provider_test.dart. -// Do not manually edit this file. - -import 'dart:async' as _i6; -import 'dart:convert' as _i7; -import 'dart:typed_data' as _i3; - -import 'package:http/src/base_request.dart' as _i8; -import 'package:http/src/client.dart' as _i5; -import 'package:http/src/response.dart' as _i2; -import 'package:http/src/streamed_response.dart' as _i4; -import 'package:mockito/mockito.dart' as _i1; - -// ignore_for_file: comment_references -// ignore_for_file: unnecessary_parenthesis - -class _FakeResponse extends _i1.Fake implements _i2.Response {} - -class _FakeUint8List extends _i1.Fake implements _i3.Uint8List {} - -class _FakeStreamedResponse extends _i1.Fake implements _i4.StreamedResponse {} - -/// A class which mocks [Client]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockClient extends _i1.Mock implements _i5.Client { - MockClient() { - _i1.throwOnMissingStub(this); - } - - @override - _i6.Future<_i2.Response> head(Uri? url, {Map? headers}) => - (super.noSuchMethod(Invocation.method(#head, [url], {#headers: headers}), - returnValue: Future.value(_FakeResponse())) - as _i6.Future<_i2.Response>); - @override - _i6.Future<_i2.Response> get(Uri? url, {Map? headers}) => - (super.noSuchMethod(Invocation.method(#get, [url], {#headers: headers}), - returnValue: Future.value(_FakeResponse())) - as _i6.Future<_i2.Response>); - @override - _i6.Future<_i2.Response> post(Uri? url, - {Map? headers, - Object? body, - _i7.Encoding? encoding}) => - (super.noSuchMethod( - Invocation.method(#post, [url], - {#headers: headers, #body: body, #encoding: encoding}), - returnValue: Future.value(_FakeResponse())) - as _i6.Future<_i2.Response>); - @override - _i6.Future<_i2.Response> put(Uri? url, - {Map? headers, - Object? body, - _i7.Encoding? encoding}) => - (super.noSuchMethod( - Invocation.method(#put, [url], - {#headers: headers, #body: body, #encoding: encoding}), - returnValue: Future.value(_FakeResponse())) - as _i6.Future<_i2.Response>); - @override - _i6.Future<_i2.Response> patch(Uri? url, - {Map? headers, - Object? body, - _i7.Encoding? encoding}) => - (super.noSuchMethod( - Invocation.method(#patch, [url], - {#headers: headers, #body: body, #encoding: encoding}), - returnValue: Future.value(_FakeResponse())) - as _i6.Future<_i2.Response>); - @override - _i6.Future<_i2.Response> delete(Uri? url, - {Map? headers, - Object? body, - _i7.Encoding? encoding}) => - (super.noSuchMethod( - Invocation.method(#delete, [url], - {#headers: headers, #body: body, #encoding: encoding}), - returnValue: Future.value(_FakeResponse())) - as _i6.Future<_i2.Response>); - @override - _i6.Future read(Uri? url, {Map? headers}) => - (super.noSuchMethod(Invocation.method(#read, [url], {#headers: headers}), - returnValue: Future.value('')) as _i6.Future); - @override - _i6.Future<_i3.Uint8List> readBytes(Uri? url, - {Map? headers}) => - (super.noSuchMethod( - Invocation.method(#readBytes, [url], {#headers: headers}), - returnValue: Future.value(_FakeUint8List())) - as _i6.Future<_i3.Uint8List>); - @override - _i6.Future<_i4.StreamedResponse> send(_i8.BaseRequest? request) => - (super.noSuchMethod(Invocation.method(#send, [request]), - returnValue: Future.value(_FakeStreamedResponse())) - as _i6.Future<_i4.StreamedResponse>); -} diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart index 6299462c7..c854da2af 100644 --- a/test/weight_screen_test.dart +++ b/test/weight_screen_test.dart @@ -20,7 +20,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; -import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; @@ -29,10 +28,9 @@ import 'package:wger/screens/weight_screen.dart'; import 'package:wger/widgets/weight/charts.dart'; import 'package:wger/widgets/weight/forms.dart'; +import 'base_provider_test.mocks.dart'; import 'utils.dart'; -import 'weight_screen_test.mocks.dart'; -@GenerateMocks([http.Client]) void main() { Widget createHomeScreen({locale = 'en'}) { final client = MockClient(); diff --git a/test/workout_plans_screen_test.dart b/test/workout_plans_screen_test.dart new file mode 100644 index 000000000..0344b423c --- /dev/null +++ b/test/workout_plans_screen_test.dart @@ -0,0 +1,106 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (C) 2020 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * wger Workout Manager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_gen/gen_l10n/app_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:mockito/mockito.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/models/workouts/workout_plan.dart'; +import 'package:wger/providers/workout_plans.dart'; +import 'package:wger/screens/workout_plans_screen.dart'; +import 'package:wger/widgets/nutrition/forms.dart'; +import 'package:wger/widgets/workouts/forms.dart'; + +import 'base_provider_test.mocks.dart'; +import 'utils.dart'; + +void main() { + Widget createHomeScreen({locale = 'en'}) { + final client = MockClient(); + when(client.delete( + any, + headers: anyNamed('headers'), + )).thenAnswer((_) async => http.Response('', 200)); + + return ChangeNotifierProvider( + create: (context) => WorkoutPlans( + testAuth, + [ + WorkoutPlan.withData(id: 1, creationDate: DateTime(2021, 01, 01), description: 'test 1'), + WorkoutPlan.withData(id: 2, creationDate: DateTime(2021, 02, 12), description: 'test 2'), + ], + client, + ), + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: WorkoutPlansScreen(), + ), + ); + } + + testWidgets('Test the widgets on the nutritional plans screen', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + //debugDumpApp(); + expect(find.text('Workout plans'), findsOneWidget); + expect(find.byType(Dismissible), findsNWidgets(2)); + expect(find.byType(ListTile), findsNWidgets(2)); + }); + + testWidgets('Test deleting an item by dragging the dismissible', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + await tester.drag(find.byKey(Key('1')), Offset(-500.0, 0.0)); + await tester.pumpAndSettle(); + + // Confirmation dialog + expect(find.byType(AlertDialog), findsOneWidget); + + // Confirm + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); + expect(find.byType(ListTile), findsOneWidget); + }); + + testWidgets('Test the form on the nutritional plan screen', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + expect(find.byType(PlanForm), findsNothing); + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + expect(find.byType(WorkoutForm), findsOneWidget); + }); + + testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen()); + + expect(find.text('1/1/2021'), findsOneWidget); + expect(find.text('2/12/2021'), findsOneWidget); + }); + + testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { + await tester.pumpWidget(createHomeScreen(locale: 'de')); + + expect(find.text('1.1.2021'), findsOneWidget); + expect(find.text('12.2.2021'), findsOneWidget); + }); +} From 0e951aa2c297bb56fb5a12c80d7efda8f21a193e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 30 Mar 2021 13:54:01 +0200 Subject: [PATCH 50/58] Bump flutter version used for tests --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e54efabd..14d590d93 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: - name: Install Flutter uses: subosito/flutter-action@v1 with: - flutter-version: '2.0.1' + flutter-version: '2.0.3' - run: dart --version - run: flutter --version From ab5226a7a448b2d71e93d61c75ba3c5d384dbb17 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 30 Mar 2021 14:08:41 +0200 Subject: [PATCH 51/58] Bump versions --- pubspec.yaml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pubspec.yaml b/pubspec.yaml index 0c8d894cf..13ff2f929 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -35,7 +35,7 @@ dependencies: json_annotation: ^4.0.0 url_launcher: ^6.0.2 charts_flutter: ^0.10.0 - flutter_typeahead: ^3.1.0 + flutter_typeahead: ^3.1.1 table_calendar: ^2.3.3 package_info: ^2.0.0 android_metadata: ^0.1.3 @@ -47,9 +47,6 @@ dev_dependencies: flutter_launcher_icons: ^0.9.0 mockito: ^5.0.2 json_serializable: ^4.0.3 - - # Note that there are incompatibilities when using a higher version. Both build - # runner and intl_translation depend on different versions of analyzer build_runner: ^1.11.5 flutter_icons: From 23c277c54c23ace215b72fff6f43f457ccfefefe Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 31 Mar 2021 14:34:07 +0200 Subject: [PATCH 52/58] Also calculate the sugar contents for meals --- lib/models/nutrition/log.dart | 16 ++++------------ lib/models/nutrition/meal_item.dart | 1 + 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/lib/models/nutrition/log.dart b/lib/models/nutrition/log.dart index 1f372cc93..2e0314815 100644 --- a/lib/models/nutrition/log.dart +++ b/lib/models/nutrition/log.dart @@ -90,19 +90,11 @@ class Log { out.energy = ingredientObj.energy * weight / 100; out.protein = ingredientObj.protein * weight / 100; out.carbohydrates = ingredientObj.carbohydrates * weight / 100; + out.carbohydratesSugar = ingredientObj.carbohydratesSugar * weight / 100; out.fat = ingredientObj.fat * weight / 100; - - if (ingredientObj.fatSaturated != null) { - out.fatSaturated = ingredientObj.fatSaturated * weight / 100; - } - - if (ingredientObj.fibres != null) { - out.fibres = ingredientObj.fibres * weight / 100; - } - - if (ingredientObj.sodium != null) { - out.sodium = ingredientObj.sodium * weight / 100; - } + out.fatSaturated = ingredientObj.fatSaturated * weight / 100; + out.fibres = ingredientObj.fibres * weight / 100; + out.sodium = ingredientObj.sodium * weight / 100; return out; } diff --git a/lib/models/nutrition/meal_item.dart b/lib/models/nutrition/meal_item.dart index c7ee4dcbf..ea8213c35 100644 --- a/lib/models/nutrition/meal_item.dart +++ b/lib/models/nutrition/meal_item.dart @@ -81,6 +81,7 @@ class MealItem { out.energy = ingredientObj.energy * weight / 100; out.protein = ingredientObj.protein * weight / 100; out.carbohydrates = ingredientObj.carbohydrates * weight / 100; + out.carbohydratesSugar = ingredientObj.carbohydratesSugar * weight / 100; out.fat = ingredientObj.fat * weight / 100; out.fatSaturated = ingredientObj.fatSaturated * weight / 100; out.fibres = ingredientObj.fibres * weight / 100; From 63584fb8f2b5013808fe16284ae50feb5a6afb57 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 31 Mar 2021 21:32:59 +0200 Subject: [PATCH 53/58] Use individual endpoints to load plan data While this results in way more requests needed, it has the great benefit of using the same data structure for reading and writing. This saves us a lot of headaches in the data modelling and we don't have to care that the info endpoints looked a bit different. --- lib/helpers/consts.dart | 3 + lib/main.dart | 37 +++---- lib/models/nutrition/log.dart | 16 ++- lib/models/nutrition/log.g.dart | 9 +- lib/models/nutrition/meal.dart | 16 +-- lib/models/nutrition/meal.g.dart | 10 +- lib/models/nutrition/meal_item.dart | 39 +++---- lib/models/nutrition/meal_item.g.dart | 17 ++- lib/models/nutrition/nutritional_plan.dart | 19 ++-- lib/models/nutrition/nutritional_plan.g.dart | 6 +- lib/models/workouts/day.dart | 23 ++-- lib/models/workouts/day.g.dart | 16 +-- lib/models/workouts/set.dart | 25 +++-- lib/models/workouts/set.g.dart | 25 +---- lib/models/workouts/setting.dart | 24 +++-- lib/models/workouts/setting.g.dart | 25 ++--- lib/models/workouts/workout_plan.dart | 20 ++-- lib/models/workouts/workout_plan.g.dart | 14 +-- lib/providers/nutrition.dart | 106 +++++++++++-------- lib/providers/workout_plans.dart | 89 ++++++++++++++-- lib/screens/dashboard.dart | 36 ++++--- lib/screens/workout_plans_screen.dart | 2 +- lib/widgets/dashboard/widgets.dart | 12 +-- lib/widgets/nutrition/forms.dart | 17 +-- lib/widgets/nutrition/meal.dart | 6 +- lib/widgets/workouts/forms.dart | 5 +- lib/widgets/workouts/gym_mode.dart | 2 +- pubspec.lock | 4 +- test/base_provider_test.dart | 2 +- test/nutritional_plans_screen_test.dart | 2 +- test/utils.dart | 6 +- test/weight_provider_test.dart | 12 +-- test/weight_screen_test.dart | 2 +- test/workout_plans_screen_test.dart | 7 +- 34 files changed, 347 insertions(+), 307 deletions(-) diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index 293583190..2a77ddfc9 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -29,3 +29,6 @@ const DEFAULT_WEIGHT_UNIT = 1; /// Default weight unit is "repetition" const DEFAULT_REPETITION_UNIT = 1; + +/// Time to locally cache values such as ingredients, etc +const DAYS_TO_CACHE = 20; diff --git a/lib/main.dart b/lib/main.dart index 80be03cff..bc1198e0d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -50,34 +50,27 @@ class MyApp extends StatelessWidget { ChangeNotifierProvider( create: (ctx) => Auth(), ), - ChangeNotifierProxyProvider( - create: (context) => WorkoutPlans(Auth(), []), - update: (context, auth, previous) => WorkoutPlans( - auth, - previous == null ? [] : previous.items, - ), - ), ChangeNotifierProxyProvider( - create: (context) => Exercises(Auth(), []), - update: (context, auth, previous) => Exercises( - auth, - previous == null ? [] : previous.items, + create: (context) => Exercises(Provider.of(context, listen: false), []), + update: (context, auth, previous) => previous != null ? previous : Exercises(auth, []), + ), + ChangeNotifierProxyProvider2( + create: (context) => WorkoutPlans( + Provider.of(context, listen: false), + Provider.of(context, listen: false), + [], ), + update: (context, auth, exercises, previous) => + previous != null ? previous : WorkoutPlans(auth, exercises, []), ), ChangeNotifierProxyProvider( - create: (context) => Nutrition(Auth(), []), - update: (context, auth, previous) => Nutrition( - auth, - previous == null ? [] : previous.items, - ), + create: (context) => Nutrition(Provider.of(context, listen: false), []), + update: (context, auth, previous) => previous != null ? previous : Nutrition(auth, []), ), ChangeNotifierProxyProvider( - create: (context) => BodyWeight(Auth(), []), - update: (context, auth, previous) => BodyWeight( - auth, - previous == null ? [] : previous.items, - ), - ) + create: (context) => BodyWeight(Provider.of(context, listen: false), []), + update: (context, auth, previous) => previous != null ? previous : BodyWeight(auth, []), + ), ], child: Consumer( builder: (ctx, auth, _) => MaterialApp( diff --git a/lib/models/nutrition/log.dart b/lib/models/nutrition/log.dart index 2e0314815..2cf827281 100644 --- a/lib/models/nutrition/log.dart +++ b/lib/models/nutrition/log.dart @@ -32,7 +32,7 @@ class Log { int? id; @JsonKey(required: true, name: 'plan') - late int planId; + int planId; @JsonKey(required: true) late DateTime datetime; @@ -46,8 +46,9 @@ class Log { late Ingredient ingredientObj; @JsonKey(required: true, name: 'weight_unit') - late int weightUnit; + late int weightUnitId; + @JsonKey(ignore: true) IngredientWeightUnit? weightUnitObj; @JsonKey(required: true, fromJson: toNum) @@ -56,20 +57,17 @@ class Log { Log({ this.id, required this.ingredientId, - //this.ingredientObj, - required this.weightUnit, - this.weightUnitObj, + required this.weightUnitId, required this.amount, required this.planId, required this.datetime, this.comment, }); - Log.fromMealItem(MealItem mealItem, int planId, [DateTime? dateTime]) { - this.ingredientId = mealItem.ingredientId!; + Log.fromMealItem(MealItem mealItem, this.planId, [DateTime? dateTime]) { + this.ingredientId = mealItem.ingredientId; this.ingredientObj = mealItem.ingredientObj; - this.weightUnit = mealItem.weightUnit!.id; - this.planId = planId; + this.weightUnitId = mealItem.weightUnitId; this.datetime = dateTime ?? DateTime.now(); this.amount = mealItem.amount; } diff --git a/lib/models/nutrition/log.g.dart b/lib/models/nutrition/log.g.dart index 278c4e80c..27cf722b8 100644 --- a/lib/models/nutrition/log.g.dart +++ b/lib/models/nutrition/log.g.dart @@ -18,11 +18,7 @@ Log _$LogFromJson(Map json) { return Log( id: json['id'] as int?, ingredientId: json['ingredient'] as int, - weightUnit: json['weight_unit'] as int, - weightUnitObj: json['weightUnitObj'] == null - ? null - : IngredientWeightUnit.fromJson( - json['weightUnitObj'] as Map), + weightUnitId: json['weight_unit'] as int, amount: toNum(json['amount'] as String?), planId: json['plan'] as int, datetime: DateTime.parse(json['datetime'] as String), @@ -36,7 +32,6 @@ Map _$LogToJson(Log instance) => { 'datetime': instance.datetime.toIso8601String(), 'comment': instance.comment, 'ingredient': instance.ingredientId, - 'weight_unit': instance.weightUnit, - 'weightUnitObj': instance.weightUnitObj, + 'weight_unit': instance.weightUnitId, 'amount': instance.amount, }; diff --git a/lib/models/nutrition/meal.dart b/lib/models/nutrition/meal.dart index 76e04cdea..ae57244d9 100644 --- a/lib/models/nutrition/meal.dart +++ b/lib/models/nutrition/meal.dart @@ -30,28 +30,28 @@ class Meal { @JsonKey(required: false) late int? id; - @JsonKey(required: false) - late int plan; + @JsonKey(name: 'plan') + late int planId; - @JsonKey(required: true, toJson: timeToString, fromJson: stringToTime) + @JsonKey(toJson: timeToString, fromJson: stringToTime) late TimeOfDay time; - @JsonKey(required: false, name: 'meal_items', defaultValue: []) + @JsonKey(ignore: true, name: 'meal_items', defaultValue: []) List mealItems = []; Meal({ this.id, int? plan, TimeOfDay? time, - //List? mealItems, + List? mealItems, }) { if (plan != null) { - this.plan = plan; + this.planId = plan; } - this.time = time ?? TimeOfDay.now(); + this.mealItems = mealItems ?? []; - this.mealItems = []; + this.time = time ?? TimeOfDay.now(); } // Boilerplate diff --git a/lib/models/nutrition/meal.g.dart b/lib/models/nutrition/meal.g.dart index 15fd7d355..20ced4e7b 100644 --- a/lib/models/nutrition/meal.g.dart +++ b/lib/models/nutrition/meal.g.dart @@ -7,20 +7,14 @@ part of 'meal.dart'; // ************************************************************************** Meal _$MealFromJson(Map json) { - $checkKeys(json, requiredKeys: const ['time']); return Meal( id: json['id'] as int?, - plan: json['plan'] as int?, time: stringToTime(json['time'] as String?), - )..mealItems = (json['meal_items'] as List?) - ?.map((e) => MealItem.fromJson(e as Map)) - .toList() ?? - []; + )..planId = json['plan'] as int; } Map _$MealToJson(Meal instance) => { 'id': instance.id, - 'plan': instance.plan, + 'plan': instance.planId, 'time': timeToString(instance.time), - 'meal_items': instance.mealItems, }; diff --git a/lib/models/nutrition/meal_item.dart b/lib/models/nutrition/meal_item.dart index ea8213c35..1dd7d107b 100644 --- a/lib/models/nutrition/meal_item.dart +++ b/lib/models/nutrition/meal_item.dart @@ -30,38 +30,33 @@ class MealItem { @JsonKey(required: true) int? id; - @JsonKey(required: false, name: 'ingredient') - int? ingredientId; + @JsonKey(required: false) + late int mealId; - @JsonKey(required: false, name: 'ingredient_obj') + @JsonKey(required: false, name: 'ingredient') + int ingredientId; + + @JsonKey(ignore: true) late Ingredient ingredientObj; - @JsonKey(required: false) - late int meal; - @JsonKey(required: false, name: 'weight_unit') - IngredientWeightUnit? weightUnit; + int weightUnitId; + + @JsonKey(ignore: true) + late IngredientWeightUnit weightUnitObj; @JsonKey(required: true, fromJson: toNum, toJson: toString) - late num amount; + num amount; MealItem({ this.id, - int? meal, - //this.ingredientObj, - ingredientId, - this.weightUnit, - num? amount, + int? mealId, + required this.ingredientId, + required this.weightUnitId, + required this.amount, }) { - if (meal != null) { - this.meal = meal; - } - - if (ingredientId != null) { - this.ingredientId = ingredientId; - } - if (amount != null) { - this.amount = amount; + if (mealId != null) { + this.mealId = mealId; } } diff --git a/lib/models/nutrition/meal_item.g.dart b/lib/models/nutrition/meal_item.g.dart index a1ab46fa9..1e4517ab0 100644 --- a/lib/models/nutrition/meal_item.g.dart +++ b/lib/models/nutrition/meal_item.g.dart @@ -10,22 +10,17 @@ MealItem _$MealItemFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'amount']); return MealItem( id: json['id'] as int?, - meal: json['meal'] as int?, - ingredientId: json['ingredient'], - weightUnit: json['weight_unit'] == null - ? null - : IngredientWeightUnit.fromJson( - json['weight_unit'] as Map), + mealId: json['mealId'] as int?, + ingredientId: json['ingredient'] as int, + weightUnitId: json['weight_unit'] as int, amount: toNum(json['amount'] as String?), - )..ingredientObj = - Ingredient.fromJson(json['ingredient_obj'] as Map); + ); } Map _$MealItemToJson(MealItem instance) => { 'id': instance.id, + 'mealId': instance.mealId, 'ingredient': instance.ingredientId, - 'ingredient_obj': instance.ingredientObj, - 'meal': instance.meal, - 'weight_unit': instance.weightUnit, + 'weight_unit': instance.weightUnitId, 'amount': toString(instance.amount), }; diff --git a/lib/models/nutrition/nutritional_plan.dart b/lib/models/nutrition/nutritional_plan.dart index 18e192804..53f899983 100644 --- a/lib/models/nutrition/nutritional_plan.dart +++ b/lib/models/nutrition/nutritional_plan.dart @@ -36,7 +36,7 @@ class NutritionalPlan { @JsonKey(required: true, name: 'creation_date', toJson: toDate) DateTime creationDate; - @JsonKey(required: false, defaultValue: []) + @JsonKey(ignore: true, defaultValue: []) List meals = []; @JsonKey(ignore: true, defaultValue: []) @@ -46,13 +46,11 @@ class NutritionalPlan { this.id, required this.description, required this.creationDate, - //List? meals, - //logs, + List? meals, + List? logs, }) { - //this.meals = meals as List ?? []; - this.meals = []; - //this.logs = logs ?? []; - this.logs = []; + this.meals = meals ?? []; + this.logs = logs ?? []; } // Boilerplate @@ -64,10 +62,8 @@ class NutritionalPlan { // This is already done on the server. It might be better to read it from there. var out = NutritionalValues(); - if (meals != null) { - for (var meal in meals) { - out.add(meal.nutritionalValues); - } + for (var meal in meals) { + out.add(meal.nutritionalValues); } return out; @@ -77,6 +73,7 @@ class NutritionalPlan { var out = {}; for (var log in logs) { final date = DateTime(log.datetime.year, log.datetime.month, log.datetime.day); + if (!out.containsKey(date)) { out[date] = NutritionalValues(); } diff --git a/lib/models/nutrition/nutritional_plan.g.dart b/lib/models/nutrition/nutritional_plan.g.dart index a1d098bc6..8f8e50d21 100644 --- a/lib/models/nutrition/nutritional_plan.g.dart +++ b/lib/models/nutrition/nutritional_plan.g.dart @@ -12,10 +12,7 @@ NutritionalPlan _$NutritionalPlanFromJson(Map json) { id: json['id'] as int?, description: json['description'] as String, creationDate: DateTime.parse(json['creation_date'] as String), - )..meals = (json['meals'] as List?) - ?.map((e) => Meal.fromJson(e as Map)) - .toList() ?? - []; + ); } Map _$NutritionalPlanToJson(NutritionalPlan instance) => @@ -23,5 +20,4 @@ Map _$NutritionalPlanToJson(NutritionalPlan instance) => 'id': instance.id, 'description': instance.description, 'creation_date': toDate(instance.creationDate), - 'meals': instance.meals.map((e) => e.toJson()).toList(), }; diff --git a/lib/models/workouts/day.dart b/lib/models/workouts/day.dart index 8867842ec..fcb2243de 100644 --- a/lib/models/workouts/day.dart +++ b/lib/models/workouts/day.dart @@ -1,6 +1,5 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:wger/models/workouts/set.dart'; -import 'package:wger/models/workouts/workout_plan.dart'; part 'day.g.dart'; @@ -9,20 +8,20 @@ class Day { @JsonKey(required: true) int? id; - @JsonKey(required: true) - late String description; - - @JsonKey(required: false, name: 'day', defaultValue: []) - List daysOfWeek = []; - - //@JsonKey(required: false) - List sets = []; - @JsonKey(required: true, name: 'training') late int workoutId; - //@JsonKey(required: true, name: 'training') - late WorkoutPlan workout; + @JsonKey(required: true) + late String description; + + @JsonKey(required: true, name: 'day') + List daysOfWeek = []; + + @JsonKey(ignore: true) + List sets = []; + + //@JsonKey(ignore: true) + //late WorkoutPlan workout; Day() { this.daysOfWeek = []; diff --git a/lib/models/workouts/day.g.dart b/lib/models/workouts/day.g.dart index 0066e3af7..9d261015d 100644 --- a/lib/models/workouts/day.g.dart +++ b/lib/models/workouts/day.g.dart @@ -7,24 +7,18 @@ part of 'day.dart'; // ************************************************************************** Day _$DayFromJson(Map json) { - $checkKeys(json, requiredKeys: const ['id', 'description', 'training']); + $checkKeys(json, + requiredKeys: const ['id', 'training', 'description', 'day']); return Day() ..id = json['id'] as int? - ..description = json['description'] as String - ..daysOfWeek = - (json['day'] as List?)?.map((e) => e as int).toList() ?? [] - ..sets = (json['sets'] as List) - .map((e) => Set.fromJson(e as Map)) - .toList() ..workoutId = json['training'] as int - ..workout = WorkoutPlan.fromJson(json['workout'] as Map); + ..description = json['description'] as String + ..daysOfWeek = (json['day'] as List).map((e) => e as int).toList(); } Map _$DayToJson(Day instance) => { 'id': instance.id, + 'training': instance.workoutId, 'description': instance.description, 'day': instance.daysOfWeek, - 'sets': instance.sets, - 'training': instance.workoutId, - 'workout': instance.workout, }; diff --git a/lib/models/workouts/set.dart b/lib/models/workouts/set.dart index 17cb55ea8..eda7ea40c 100644 --- a/lib/models/workouts/set.dart +++ b/lib/models/workouts/set.dart @@ -18,28 +18,27 @@ class Set { late int day; @JsonKey(required: true) - late int order; + int? order; - //@JsonKey(required: true) + @JsonKey(ignore: true) List exercisesObj = []; - @JsonKey(required: false, name: 'exercises') + @JsonKey(ignore: true) List exercisesIds = []; - @JsonKey(required: false) + @JsonKey(ignore: true) List settings = []; - /// Computed settings - @JsonKey(required: false) + /// Computed settings (instead of 4x10 this has [10, 10, 10, 10]), used for + /// the gym mode where the individual values are used + @JsonKey(ignore: true) List settingsComputed = []; - Set() { - this.sets = sets; - this.exercisesObj = []; - this.exercisesIds = exercisesObj.map((e) => e.id).toList(); - this.settings; - this.settingsComputed; - } + Set({ + required this.day, + required this.sets, + this.order, + }); Set.withData({ this.id, diff --git a/lib/models/workouts/set.g.dart b/lib/models/workouts/set.g.dart index b063cb608..38b18cb7e 100644 --- a/lib/models/workouts/set.g.dart +++ b/lib/models/workouts/set.g.dart @@ -8,22 +8,11 @@ part of 'set.dart'; Set _$SetFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'sets', 'order']); - return Set() - ..id = json['id'] as int? - ..sets = json['sets'] as int - ..day = json['exerciseday'] as int - ..order = json['order'] as int - ..exercisesObj = (json['exercisesObj'] as List) - .map((e) => Exercise.fromJson(e as Map)) - .toList() - ..exercisesIds = - (json['exercises'] as List).map((e) => e as int).toList() - ..settings = (json['settings'] as List) - .map((e) => Setting.fromJson(e as Map)) - .toList() - ..settingsComputed = (json['settingsComputed'] as List) - .map((e) => Setting.fromJson(e as Map)) - .toList(); + return Set( + day: json['exerciseday'] as int, + sets: json['sets'] as int, + order: json['order'] as int?, + )..id = json['id'] as int?; } Map _$SetToJson(Set instance) => { @@ -31,8 +20,4 @@ Map _$SetToJson(Set instance) => { 'sets': instance.sets, 'exerciseday': instance.day, 'order': instance.order, - 'exercisesObj': instance.exercisesObj, - 'exercises': instance.exercisesIds, - 'settings': instance.settings, - 'settingsComputed': instance.settingsComputed, }; diff --git a/lib/models/workouts/setting.dart b/lib/models/workouts/setting.dart index 7dbf9a521..d56387fa1 100644 --- a/lib/models/workouts/setting.dart +++ b/lib/models/workouts/setting.dart @@ -1,6 +1,8 @@ import 'package:json_annotation/json_annotation.dart'; import 'package:wger/helpers/json.dart'; import 'package:wger/models/exercises/exercise.dart'; +import 'package:wger/models/workouts/repetition_unit.dart'; +import 'package:wger/models/workouts/weight_unit.dart'; part 'setting.g.dart'; @@ -22,7 +24,7 @@ class Setting { late int repetitionUnitId; @JsonKey(ignore: true) - late int repetitionUnitObj; + late RepetitionUnit repetitionUnitObj; @JsonKey(required: true) late int reps; @@ -34,19 +36,29 @@ class Setting { late int weightUnitId; @JsonKey(ignore: true) - late int weightUnitObj; + late WeightUnit weightUnitObj; - @JsonKey(required: true, defaultValue: '') + @JsonKey(required: true) late String comment = ''; - @JsonKey(required: false, defaultValue: '') - late String rir = ''; + @JsonKey(required: true) + String? rir = ''; // Generated by Server @JsonKey(required: false) late String repsText; - Setting(); + Setting({ + this.id, + required this.setId, + required this.exerciseId, + required this.repetitionUnitId, + required this.reps, + required this.weightUnitId, + required this.comment, + required this.rir, + required this.repsText, + }); Setting.withData({ this.id, diff --git a/lib/models/workouts/setting.g.dart b/lib/models/workouts/setting.g.dart index e80e60825..b4d6936c9 100644 --- a/lib/models/workouts/setting.g.dart +++ b/lib/models/workouts/setting.g.dart @@ -15,19 +15,20 @@ Setting _$SettingFromJson(Map json) { 'reps', 'weight', 'weight_unit', - 'comment' + 'comment', + 'rir' ]); - return Setting() - ..id = json['id'] as int? - ..setId = json['set'] as int - ..exerciseId = json['exercise'] as int - ..repetitionUnitId = json['repetition_unit'] as int - ..reps = json['reps'] as int - ..weight = toNum(json['weight'] as String?) - ..weightUnitId = json['weight_unit'] as int - ..comment = json['comment'] as String? ?? '' - ..rir = json['rir'] as String? ?? '' - ..repsText = json['repsText'] as String; + return Setting( + id: json['id'] as int?, + setId: json['set'] as int, + exerciseId: json['exercise'] as int, + repetitionUnitId: json['repetition_unit'] as int, + reps: json['reps'] as int, + weightUnitId: json['weight_unit'] as int, + comment: json['comment'] as String, + rir: json['rir'] as String?, + repsText: json['repsText'] as String, + )..weight = toNum(json['weight'] as String?); } Map _$SettingToJson(Setting instance) => { diff --git a/lib/models/workouts/workout_plan.dart b/lib/models/workouts/workout_plan.dart index 7251911de..9d769ed7f 100644 --- a/lib/models/workouts/workout_plan.dart +++ b/lib/models/workouts/workout_plan.dart @@ -29,25 +29,23 @@ class WorkoutPlan { int? id; @JsonKey(required: true, name: 'creation_date') - late DateTime creationDate; + DateTime creationDate; @JsonKey(required: true, name: 'comment') - late String description; + String description; - @JsonKey(required: false, defaultValue: [], name: 'days') - late List days = []; + @JsonKey(ignore: true) + List days = []; - @JsonKey(ignore: true, defaultValue: []) - late List logs = []; + @JsonKey(ignore: true) + List logs = []; - WorkoutPlan(); - - WorkoutPlan.withData({ + WorkoutPlan({ this.id, required this.creationDate, required this.description, - days, - logs, + List? days, + List? logs, }) { this.days = days ?? []; this.logs = logs ?? []; diff --git a/lib/models/workouts/workout_plan.g.dart b/lib/models/workouts/workout_plan.g.dart index 04c54f818..176b71c61 100644 --- a/lib/models/workouts/workout_plan.g.dart +++ b/lib/models/workouts/workout_plan.g.dart @@ -8,14 +8,11 @@ part of 'workout_plan.dart'; WorkoutPlan _$WorkoutPlanFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'creation_date', 'comment']); - return WorkoutPlan() - ..id = json['id'] as int? - ..creationDate = DateTime.parse(json['creation_date'] as String) - ..description = json['comment'] as String - ..days = (json['days'] as List?) - ?.map((e) => Day.fromJson(e as Map)) - .toList() ?? - []; + return WorkoutPlan( + id: json['id'] as int?, + creationDate: DateTime.parse(json['creation_date'] as String), + description: json['comment'] as String, + ); } Map _$WorkoutPlanToJson(WorkoutPlan instance) => @@ -23,5 +20,4 @@ Map _$WorkoutPlanToJson(WorkoutPlan instance) => 'id': instance.id, 'creation_date': instance.creationDate.toIso8601String(), 'comment': instance.description, - 'days': instance.days, }; diff --git a/lib/providers/nutrition.dart b/lib/providers/nutrition.dart index 79c7eede1..7b1173359 100644 --- a/lib/providers/nutrition.dart +++ b/lib/providers/nutrition.dart @@ -23,6 +23,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/models/http_exception.dart'; import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/log.dart'; @@ -33,10 +34,7 @@ import 'package:wger/providers/auth.dart'; import 'package:wger/providers/base_provider.dart'; class Nutrition extends WgerBaseProvider with ChangeNotifier { - static const DAYS_TO_CACHE = 20; - static const _nutritionalPlansPath = 'nutritionplan'; - static const _nutritionalPlansInfoPath = 'nutritionplaninfo'; static const _mealPath = 'meal'; static const _mealItemPath = 'mealitem'; static const _ingredientPath = 'ingredient'; @@ -69,45 +67,62 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { Meal? findMealById(int id) { for (var plan in _plans) { var meal = plan.meals.firstWhere((plan) => plan.id == id); - if (meal != null) { - return meal; - } + return meal; } return null; } - Future> fetchAndSetPlans() async { - final data = - await fetch(makeUrl(_nutritionalPlansInfoPath, query: {'ordering': '-creation_date'})); - final List loadedPlans = []; + /// Fetches and sets all nutritional plans + Future fetchAndSetAllPlans() async { + final data = await fetch(makeUrl(_nutritionalPlansPath)); for (final entry in data['results']) { - try { - //log(entry.toString()); - loadedPlans.add(NutritionalPlan.fromJson(entry)); - } catch (e) { - log(e.toString()); - //log(); - } + await fetchAndSetPlan(entry['id']); } - - _plans = loadedPlans; - notifyListeners(); - return loadedPlans; } + /// Fetches and sets the given nutritional plan Future fetchAndSetPlan(int planId) async { - //fetchAndSet - final data = await fetch(makeUrl(_nutritionalPlansInfoPath, id: planId)); - final plan = NutritionalPlan.fromJson(data); + // Plan + final planData = await fetch(makeUrl(_nutritionalPlansPath, id: planId)); + final plan = NutritionalPlan.fromJson(planData); + + // Meals + List meals = []; + final mealsData = await fetch(makeUrl(_mealPath, query: {'plan': planId.toString()})); + for (final mealEntry in mealsData['results']) { + List mealItems = []; + final meal = Meal.fromJson(mealEntry); + + // Meal items + final mealItemsData = await fetch( + makeUrl(_mealItemPath, query: {'meal': meal.id.toString()}), + ); + for (final mealItemEntry in mealItemsData['results']) { + final mealItem = MealItem.fromJson(mealItemEntry); + mealItem.ingredientObj = await fetchIngredient(mealItem.ingredientId); + mealItems.add(mealItem); + } + + meal.mealItems = mealItems; + meals.add(meal); + } + plan.meals = meals; + + // Logs await fetchAndSetLogs(plan); + // ... and done + _plans.add(plan); + _plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); + notifyListeners(); return plan; } Future postPlan(NutritionalPlan planData) async { final data = await post(planData.toJson(), makeUrl(_nutritionalPlansPath)); final plan = NutritionalPlan.fromJson(data); - _plans.insert(0, plan); + _plans.add(plan); + _plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); notifyListeners(); return plan; } @@ -157,7 +172,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { /// Deletes a meal Future deleteMeal(Meal meal) async { // Get the meal - var plan = findById(meal.plan); + var plan = findById(meal.planId); final mealIndex = plan.meals.indexWhere((e) => e.id == meal.id); var existingMeal = plan.meals[mealIndex]; plan.meals.removeAt(mealIndex); @@ -178,7 +193,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { final data = await post(mealItem.toJson(), makeUrl(_mealItemPath)); mealItem = MealItem.fromJson(data); - mealItem.ingredientObj = await fetchIngredient(mealItem.ingredientId!); + mealItem.ingredientObj = await fetchIngredient(mealItem.ingredientId); meal.mealItems.add(mealItem); notifyListeners(); @@ -188,7 +203,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { /// Deletes a meal Future deleteMealItem(MealItem mealItem) async { // Get the meal - var meal = findMealById(mealItem.meal)!; + var meal = findMealById(mealItem.mealId)!; final mealItemIndex = meal.mealItems.indexWhere((e) => e.id == mealItem.id); var existingMealItem = meal.mealItems[mealItemIndex]; meal.mealItems.removeAt(mealItemIndex); @@ -207,23 +222,26 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { /// /// If the ingredient is not known locally, it is fetched from the server Future fetchIngredient(int ingredientId) async { - var ingredient = _ingredients.firstWhere((e) => e.id == ingredientId); - if (ingredient != null) { + Ingredient ingredient; + + try { + ingredient = _ingredients.firstWhere((e) => e.id == ingredientId); + return ingredient; + + // Get ingredient from the server and save to cache + } on StateError catch (e) { + final data = await fetch(makeUrl(_ingredientPath, id: ingredientId)); + ingredient = Ingredient.fromJson(data); + _ingredients.add(ingredient); + + final prefs = await SharedPreferences.getInstance(); + final ingredientData = json.decode(prefs.getString('ingredientData')!); + ingredientData['ingredients'].add(ingredient.toJson()); + prefs.setString('ingredientData', json.encode(ingredientData)); + log("Saved ingredient '${ingredient.name}' to cache."); + return ingredient; } - - // Get ingredient from the server and save to cache - final data = await fetch(makeUrl(_ingredientPath, id: ingredientId)); - ingredient = Ingredient.fromJson(data); - _ingredients.add(ingredient); - - final prefs = await SharedPreferences.getInstance(); - final ingredientData = json.decode(prefs.getString('ingredientData')!); - ingredientData['ingredients'].add(ingredient.toJson()); - prefs.setString('ingredientData', json.encode(ingredientData)); - log("Saved ingredient '${ingredient.name}' to cache."); - - return ingredient; } /// Loads the available ingredients from the local storage @@ -277,7 +295,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier { Future logMealToDiary(Meal meal) async { //var meal = findMealById(mealId); for (var item in meal.mealItems) { - final plan = findById(meal.plan); + final plan = findById(meal.planId); Log log = Log.fromMealItem(item, plan.id!); //log.planId = plan.id; //log.datetime = DateTime.now(); diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index 255300c8c..43857d5ec 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -36,10 +36,9 @@ import 'package:wger/models/workouts/weight_unit.dart'; import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/providers/auth.dart'; import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/exercises.dart'; class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { - static const DAYS_TO_CACHE = 10; - static const _workoutPlansUrlPath = 'workout'; static const _daysUrlPath = 'day'; static const _setsUrlPath = 'set'; @@ -50,12 +49,14 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { static const _repetitionUnitUrlPath = 'setting-repetitionunit'; WorkoutPlan? _currentPlan; + Exercises _exercises; List _workoutPlans = []; List _weightUnits = []; List _repetitionUnit = []; - WorkoutPlans(Auth auth, List entries, [http.Client? client]) - : this._workoutPlans = entries, + WorkoutPlans(Auth auth, Exercises exercises, List entries, [http.Client? client]) + : this._exercises = exercises, + this._workoutPlans = entries, super(auth, client); List get items { @@ -114,6 +115,74 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { /* * Workouts */ + + Future fetchAndSetAllPlans() async { + final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'})); + for (final entry in data['results']) { + await fetchAndSetWorkoutPlan(entry['id']); + } + + notifyListeners(); + } + + Future fetchAndSetWorkoutPlan(int workoutId) async { + // Plan + final planData = await fetch(makeUrl(_workoutPlansUrlPath, id: workoutId)); + final plan = WorkoutPlan.fromJson(planData); + + // Days + List days = []; + final daysData = await fetch(makeUrl(_daysUrlPath, query: {'training': workoutId.toString()})); + for (final dayEntry in daysData['results']) { + final day = Day.fromJson(dayEntry); + + // Sets + List sets = []; + final setData = await fetch(makeUrl(_setsUrlPath, query: {'exerciseday': day.id.toString()})); + for (final setEntry in setData['results']) { + final workoutSet = Set.fromJson(setEntry); + + // Settings + List settings = []; + final settingData = await fetch( + makeUrl(_settingsUrlPath, query: {'set': workoutSet.id.toString()}), + ); + for (final settingEntry in settingData['results']) { + final workoutSetting = Setting.fromJson(settingEntry); + + workoutSetting.exerciseObj = _exercises.findById(workoutSetting.exerciseId); + workoutSetting.weightUnitObj = _weightUnits.firstWhere( + (e) => e.id == workoutSetting.weightUnitId, + ); + workoutSetting.repetitionUnitObj = _repetitionUnit.firstWhere( + (e) => e.id == workoutSetting.repetitionUnitId, + ); + if (!workoutSet.exercisesIds.contains(workoutSetting.exerciseId)) { + workoutSet.addExercise(workoutSetting.exerciseObj); + } + workoutSetting.repsText = 'FIXME!'; + settings.add(workoutSetting); + } + workoutSet.settings = settings; + sets.add(workoutSet); + } + day.sets = sets; + days.add(day); + } + plan.days = days; + + // Logs + final logData = await fetch(makeUrl(_logsUrlPath, query: {'workout': workoutId.toString()})); + for (final entry in logData['results']) { + plan.logs.add(Log.fromJson(entry)); + } + + // ... and done + _workoutPlans.add(plan); + _workoutPlans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); + notifyListeners(); + } + Future fetchAndSetWorkouts() async { final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'})); final List loadedWorkoutPlans = []; @@ -126,12 +195,14 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { notifyListeners(); } + // TODO: delete Future setAllFullWorkouts() async { for (var plan in _workoutPlans) { setFullWorkout(plan.id!); } } + // TODO: delete Future setFullWorkout(int workoutId) async { final data = await fetch(makeUrl( _workoutPlansUrlPath, @@ -310,15 +381,15 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { // Load units from cache, if available final prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('workoutUnits')) { - final workoutData = json.decode(prefs.getString('workoutUnits')!); - if (DateTime.parse(workoutData['expiresIn']).isAfter(DateTime.now())) { - workoutData['repetitionUnits'].forEach( + final unitData = json.decode(prefs.getString('workoutUnits')!); + if (DateTime.parse(unitData['expiresIn']).isAfter(DateTime.now())) { + unitData['repetitionUnits'].forEach( (e) => _repetitionUnit.add(RepetitionUnit.fromJson(e)), ); - workoutData['weightUnit'].forEach( + unitData['weightUnit'].forEach( (e) => _weightUnits.add(WeightUnit.fromJson(e)), ); - log("Read workout units data from cache. Valid till ${workoutData['expiresIn']}"); + log("Read workout units data from cache. Valid till ${unitData['expiresIn']}"); return; } } diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index 301704877..f08c51247 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -37,6 +37,8 @@ class DashboardScreen extends StatefulWidget { } class _DashboardScreenState extends State { + Future? _initialData; + Widget getAppBar() { return AppBar( title: Text(AppLocalizations.of(context)!.labelDashboard), @@ -44,8 +46,16 @@ class _DashboardScreenState extends State { ); } + @override + void initState() { + super.initState(); + + // Loading data here, since the build method can be called more than once + _initialData = _loadEntries(); + } + /// Load initial data from the server - Future _loadEntries(BuildContext context) async { + Future _loadEntries() async { if (!Provider.of(context, listen: false).dataInit) { Provider.of(context, listen: false).setServerVersion(); @@ -53,23 +63,25 @@ class _DashboardScreenState extends State { await Provider.of(context, listen: false).fetchAndSetExercises(); // Nutrition - Nutrition nutritionProvider = Provider.of(context, listen: false); - await nutritionProvider.fetchIngredientsFromCache(); - await nutritionProvider.fetchAndSetPlans(); - await nutritionProvider.fetchAndSetAllLogs(); + await Provider.of(context, listen: false).fetchIngredientsFromCache(); + await Provider.of(context, listen: false).fetchAndSetAllPlans(); + await Provider.of(context, listen: false).fetchAndSetAllLogs(); // Workouts - WorkoutPlans workoutProvider = Provider.of(context, listen: false); - await workoutProvider.fetchAndSetUnits(); - await workoutProvider.fetchAndSetWorkouts(); - await workoutProvider.setAllFullWorkouts(); - if (workoutProvider.activePlan != null) { - workoutProvider.setCurrentPlan(workoutProvider.activePlan!.id!); + await Provider.of(context, listen: false).fetchAndSetUnits(); + await Provider.of(context, listen: false).fetchAndSetAllPlans(); + //await Provider.of(context, listen: false).fetchAndSetWorkouts(); + //await Provider.of(context, listen: false).setAllFullWorkouts(); + if (Provider.of(context, listen: false).activePlan != null) { + Provider.of(context, listen: false).setCurrentPlan( + Provider.of(context, listen: false).activePlan!.id!, + ); } // Weight await Provider.of(context, listen: false).fetchAndSetEntries(); } + Provider.of(context, listen: false).dataInit = true; } @@ -79,7 +91,7 @@ class _DashboardScreenState extends State { appBar: getAppBar() as PreferredSizeWidget?, drawer: AppDrawer(), body: FutureBuilder( - future: _loadEntries(context), + future: _initialData, builder: (ctx, authResultSnapshot) => authResultSnapshot.connectionState == ConnectionState.waiting ? Column( diff --git a/lib/screens/workout_plans_screen.dart b/lib/screens/workout_plans_screen.dart index ace75a14f..630b4a12a 100644 --- a/lib/screens/workout_plans_screen.dart +++ b/lib/screens/workout_plans_screen.dart @@ -47,7 +47,7 @@ class _WorkoutPlansScreenState extends State { showFormBottomSheet( context, AppLocalizations.of(context)!.newWorkout, - WorkoutForm(WorkoutPlan()), + WorkoutForm(WorkoutPlan(creationDate: DateTime.now(), description: '')), ); }, ), diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 83d6aa47d..029f98768 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -239,12 +239,6 @@ class _DashboardWorkoutWidgetState extends State { late WorkoutPlan _workoutPlan; var showDetail = false; - @override - void initState() { - // TODO: implement initState - super.initState(); - } - @override Widget build(BuildContext context) { WorkoutPlan? _workoutPlan = Provider.of(context, listen: false).activePlan; @@ -266,11 +260,11 @@ class _DashboardWorkoutWidgetState extends State { children: [ Text(s.exerciseObj.name), Text(s.repsText), - SizedBox(height: 10), + SizedBox(height: 5), ], ); }).toList(), - Divider(), + SizedBox(height: 7), ], )); }); @@ -310,7 +304,7 @@ class _DashboardWorkoutWidgetState extends State { : NothingFound( AppLocalizations.of(context)!.noWorkoutPlans, AppLocalizations.of(context)!.newWorkout, - WorkoutForm(WorkoutPlan()), + WorkoutForm(WorkoutPlan(creationDate: DateTime.now(), description: '')), ), Row( mainAxisAlignment: MainAxisAlignment.end, diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index 07707417f..b1f876304 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -113,24 +113,11 @@ class MealItemForm extends StatelessWidget { Meal _meal; late MealItem _mealItem; - //var mealItemData = {}; - MealItemForm(this._meal, [mealItem]) { - this._mealItem = mealItem ?? MealItem(meal: _meal.id); + this._mealItem = mealItem; + //this._mealItem = mealItem ?? MealItem(mealId: _meal.id); } - /* - MealItemForm(this._meal, [MealItem? mealItem]) { - //this.meal = meal; - mealItemData['meal'] = _meal.id; - if (mealItem != null) { - mealItemData['ingredientId'] = mealItem.ingredientId; - mealItemData['amount'] = mealItem.amount; - } - //this.mealItem = mealItem ?? MealItem(); - } - */ - final _form = GlobalKey(); final _ingredientController = TextEditingController(); final _amountController = TextEditingController(); diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index b46782896..46287845e 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -95,9 +95,9 @@ class MealItemWidget extends StatelessWidget { @override Widget build(BuildContext context) { - String unit = _item.weightUnit == null + String unit = _item.weightUnitId == null ? AppLocalizations.of(context)!.g - : _item.weightUnit!.weightUnit.name; + : _item.weightUnitObj.weightUnit.name; final values = _item.nutritionalValues; return Container( @@ -173,7 +173,7 @@ class DismissibleMealHeader extends StatelessWidget { showFormBottomSheet( context, AppLocalizations.of(context)!.edit, - MealForm(_meal.plan, _meal), + MealForm(_meal.planId, _meal), ); }, child: Dismissible( diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index db862dd0d..c80f2a122 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -212,7 +212,7 @@ class _DayFormWidgetState extends State { class SetFormWidget extends StatefulWidget { Day _day; - Set _set = Set(); + late Set _set; SetFormWidget(Day this._day, [Set? set]) { //this._day = day; @@ -316,9 +316,12 @@ class _SetFormWidgetState extends State { widget._set.settings = []; for (var exercise in widget._set.exercisesObj) { for (int loop = 0; loop < widget._set.sets; loop++) { + /* Setting setting = Setting(); setting.exerciseObj = exercise; widget._set.settings.add(setting); + + */ } } diff --git a/lib/widgets/workouts/gym_mode.dart b/lib/widgets/workouts/gym_mode.dart index 959c7082d..b9eeea0f6 100644 --- a/lib/widgets/workouts/gym_mode.dart +++ b/lib/widgets/workouts/gym_mode.dart @@ -160,7 +160,7 @@ class LogPage extends StatelessWidget { } if (_setting.rir != null) { - _rirController.text = _setting.rir; + _rirController.text = _setting.rir!; } _log.date = DateTime.now(); diff --git a/pubspec.lock b/pubspec.lock index 4fee1ffc1..cbce0116a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -281,7 +281,7 @@ packages: name: flutter_typeahead url: "https://pub.dartlang.org" source: hosted - version: "3.1.0" + version: "3.1.1" flutter_web_plugins: dependency: transitive description: flutter @@ -725,7 +725,7 @@ packages: name: win32 url: "https://pub.dartlang.org" source: hosted - version: "2.0.4" + version: "2.0.5" xdg_directories: dependency: transitive description: diff --git a/test/base_provider_test.dart b/test/base_provider_test.dart index 3184667de..9392cda94 100644 --- a/test/base_provider_test.dart +++ b/test/base_provider_test.dart @@ -27,7 +27,7 @@ import 'utils.dart'; void main() { group('test base provider', () { test('Test the makeUrl helper', () async { - final WgerBaseProvider provider = WgerBaseProvider(testAuth); + final WgerBaseProvider provider = WgerBaseProvider(testAuthProvider); expect( Uri.https('localhost', '/api/v2/endpoint/'), diff --git a/test/nutritional_plans_screen_test.dart b/test/nutritional_plans_screen_test.dart index 8cc74e1bc..10c8ffee8 100644 --- a/test/nutritional_plans_screen_test.dart +++ b/test/nutritional_plans_screen_test.dart @@ -40,7 +40,7 @@ void main() { return ChangeNotifierProvider( create: (context) => Nutrition( - testAuth, + testAuthProvider, [ NutritionalPlan(id: 1, description: 'test plan 1', creationDate: DateTime(2021, 01, 01)), NutritionalPlan(id: 2, description: 'test plan 2', creationDate: DateTime(2021, 01, 10)), diff --git a/test/utils.dart b/test/utils.dart index 8b068d32c..2ca30996e 100644 --- a/test/utils.dart +++ b/test/utils.dart @@ -17,8 +17,12 @@ */ import 'package:wger/providers/auth.dart'; +import 'package:wger/providers/exercises.dart'; // Test Auth provider -final Auth testAuth = Auth() +final Auth testAuthProvider = Auth() ..token = 'FooBar' ..serverUrl = 'https://localhost'; + +// Test Exercises provider +final Exercises testExercisesProvider = Exercises(testAuthProvider, []); diff --git a/test/weight_provider_test.dart b/test/weight_provider_test.dart index b29b78954..490bc11ae 100644 --- a/test/weight_provider_test.dart +++ b/test/weight_provider_test.dart @@ -38,7 +38,7 @@ void main() { when(client.get( Uri.https('localhost', 'api/v2/weightentry/', {'ordering': '-date'}), headers: { - HttpHeaders.authorizationHeader: 'Token ${testAuth.token}', + HttpHeaders.authorizationHeader: 'Token ${testAuthProvider.token}', HttpHeaders.userAgentHeader: 'wger Workout Manager App', }, )).thenAnswer((_) async => http.Response( @@ -48,7 +48,7 @@ void main() { 200)); // Load the entries - BodyWeight provider = BodyWeight(testAuth, [], client); + BodyWeight provider = BodyWeight(testAuthProvider, [], client); await provider.fetchAndSetEntries(); // Check that everything is ok @@ -62,7 +62,7 @@ void main() { // Mock the server response when(client.post(Uri.https('localhost', 'api/v2/weightentry/'), headers: { - HttpHeaders.authorizationHeader: 'Token ${testAuth.token}', + HttpHeaders.authorizationHeader: 'Token ${testAuthProvider.token}', HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: 'wger Workout Manager App', }, @@ -72,7 +72,7 @@ void main() { // POST the data to the server final WeightEntry weightEntry = WeightEntry(date: DateTime(2021, 1, 1), weight: 80); - final BodyWeight provider = BodyWeight(testAuth, [], client); + final BodyWeight provider = BodyWeight(testAuthProvider, [], client); final WeightEntry weightEntryNew = await provider.addEntry(weightEntry); // Check that the server response is what we expect @@ -88,14 +88,14 @@ void main() { when(client.delete( Uri.https('localhost', 'api/v2/weightentry/4/'), headers: { - HttpHeaders.authorizationHeader: 'Token ${testAuth.token}', + HttpHeaders.authorizationHeader: 'Token ${testAuthProvider.token}', HttpHeaders.userAgentHeader: 'wger Workout Manager App', }, )).thenAnswer((_) async => http.Response('', 200)); // DELETE the data from the server final BodyWeight provider = BodyWeight( - testAuth, + testAuthProvider, [ WeightEntry(id: 4, weight: 80, date: DateTime(2021, 1, 1)), WeightEntry(id: 2, weight: 100, date: DateTime(2021, 2, 2)), diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart index c854da2af..de1dbafc9 100644 --- a/test/weight_screen_test.dart +++ b/test/weight_screen_test.dart @@ -47,7 +47,7 @@ void main() { return ChangeNotifierProvider( create: (context) => BodyWeight( - testAuth, + testAuthProvider, [ WeightEntry(id: 1, weight: 80, date: DateTime(2021, 01, 01)), WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)), diff --git a/test/workout_plans_screen_test.dart b/test/workout_plans_screen_test.dart index 0344b423c..5975fecbd 100644 --- a/test/workout_plans_screen_test.dart +++ b/test/workout_plans_screen_test.dart @@ -41,10 +41,11 @@ void main() { return ChangeNotifierProvider( create: (context) => WorkoutPlans( - testAuth, + testAuthProvider, + testExercisesProvider, [ - WorkoutPlan.withData(id: 1, creationDate: DateTime(2021, 01, 01), description: 'test 1'), - WorkoutPlan.withData(id: 2, creationDate: DateTime(2021, 02, 12), description: 'test 2'), + WorkoutPlan(id: 1, creationDate: DateTime(2021, 01, 01), description: 'test 1'), + WorkoutPlan(id: 2, creationDate: DateTime(2021, 02, 12), description: 'test 2'), ], client, ), From bf9abea7aa32dc98271b9453c6420c5b7700be88 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 2 Apr 2021 12:03:15 +0200 Subject: [PATCH 54/58] Render forms in own scaffold This eliminates many of the overflow problems from the bottom sheet --- lib/l10n/app_en.arb | 9 + lib/main.dart | 2 + lib/models/workouts/setting.dart | 7 +- lib/models/workouts/setting.g.dart | 2 - lib/screens/form_screen.dart | 62 ++++ lib/screens/nutritional_plan_screen.dart | 11 +- lib/screens/nutritional_plans_screen.dart | 12 +- lib/screens/weight_screen.dart | 20 +- lib/screens/workout_plan_screen.dart | 11 +- lib/screens/workout_plans_screen.dart | 11 +- lib/widgets/core/bottom_sheet.dart | 46 --- lib/widgets/dashboard/widgets.dart | 20 +- lib/widgets/nutrition/meal.dart | 22 +- .../nutrition/nutritional_plan_detail.dart | 11 +- lib/widgets/weight/entries_list.dart | 11 +- lib/widgets/workouts/day.dart | 13 +- lib/widgets/workouts/forms.dart | 282 +++++++++--------- lib/widgets/workouts/workout_plan_detail.dart | 12 +- test/nutritional_plans_screen_test.dart | 4 + test/weight_screen_test.dart | 4 + test/workout_plans_screen_test.dart | 4 + 21 files changed, 314 insertions(+), 262 deletions(-) create mode 100644 lib/screens/form_screen.dart delete mode 100644 lib/widgets/core/bottom_sheet.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8fa3e88b9..c60a179a3 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -260,6 +260,15 @@ "@enterValue": { "description": "Error message when the user hasn't entered a value on a required field" }, + "enterCharacters": "Please enter between {min} and {max} characters", + "@enterCharacters": { + "description": "Error message when the user hasn't entered the correct number of characters in a form", + "type": "text", + "placeholders": { + "min": {}, + "max": {} + } + }, "enterValidNumber": "Please enter a valid number", "@enterValidNumber": { "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" diff --git a/lib/main.dart b/lib/main.dart index bc1198e0d..a0a2a4586 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -25,6 +25,7 @@ import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/workout_plans.dart'; import 'package:wger/screens/auth_screen.dart'; import 'package:wger/screens/dashboard.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/gym_mode.dart'; import 'package:wger/screens/home_tabs_screen.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; @@ -94,6 +95,7 @@ class MyApp extends StatelessWidget { GymModeScreen.routeName: (ctx) => GymModeScreen(), NutritionScreen.routeName: (ctx) => NutritionScreen(), NutritionalPlanScreen.routeName: (ctx) => NutritionalPlanScreen(), + FormScreen.routeName: (ctx) => FormScreen(), }, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, diff --git a/lib/models/workouts/setting.dart b/lib/models/workouts/setting.dart index d56387fa1..91709eed9 100644 --- a/lib/models/workouts/setting.dart +++ b/lib/models/workouts/setting.dart @@ -45,8 +45,8 @@ class Setting { String? rir = ''; // Generated by Server - @JsonKey(required: false) - late String repsText; + @JsonKey(ignore: true) + late String repsText = ''; Setting({ this.id, @@ -57,7 +57,6 @@ class Setting { required this.weightUnitId, required this.comment, required this.rir, - required this.repsText, }); Setting.withData({ @@ -78,6 +77,8 @@ class Setting { } } + Setting.empty(); + // Boilerplate factory Setting.fromJson(Map json) => _$SettingFromJson(json); Map toJson() => _$SettingToJson(this); diff --git a/lib/models/workouts/setting.g.dart b/lib/models/workouts/setting.g.dart index b4d6936c9..62be72439 100644 --- a/lib/models/workouts/setting.g.dart +++ b/lib/models/workouts/setting.g.dart @@ -27,7 +27,6 @@ Setting _$SettingFromJson(Map json) { weightUnitId: json['weight_unit'] as int, comment: json['comment'] as String, rir: json['rir'] as String?, - repsText: json['repsText'] as String, )..weight = toNum(json['weight'] as String?); } @@ -41,5 +40,4 @@ Map _$SettingToJson(Setting instance) => { 'weight_unit': instance.weightUnitId, 'comment': instance.comment, 'rir': instance.rir, - 'repsText': instance.repsText, }; diff --git a/lib/screens/form_screen.dart b/lib/screens/form_screen.dart new file mode 100644 index 000000000..510af8730 --- /dev/null +++ b/lib/screens/form_screen.dart @@ -0,0 +1,62 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (C) 2020 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * wger Workout Manager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import 'package:flutter/material.dart'; + +/// Arguments passed to the form screen +class FormScreenArguments { + /// Title + final String title; + + /// Widget to render, typically a form + final Widget widget; + + /// Flag indicating whether to render the content has a list view (e.g. larger + /// forms that use an autocompleter, etc) or not (smnall forms, content will + /// get pushed down) + final bool hasListView; + FormScreenArguments(this.title, this.widget, [this.hasListView = false]); +} + +class FormScreen extends StatelessWidget { + static const routeName = '/form'; + + @override + Widget build(BuildContext context) { + final FormScreenArguments args = + ModalRoute.of(context)!.settings.arguments as FormScreenArguments; + + return Scaffold( + appBar: AppBar(title: Text(args.title)), + body: args.hasListView + ? Padding( + padding: const EdgeInsets.all(15.0), + child: args.widget, + ) + : Column( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Padding( + padding: const EdgeInsets.all(15.0), + child: args.widget, + ), + ], + ), + ); + } +} diff --git a/lib/screens/nutritional_plan_screen.dart b/lib/screens/nutritional_plan_screen.dart index 5a06507a5..64d828685 100644 --- a/lib/screens/nutritional_plan_screen.dart +++ b/lib/screens/nutritional_plan_screen.dart @@ -21,7 +21,7 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/providers/nutrition.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/nutrition/nutritional_plan_detail.dart'; @@ -53,10 +53,13 @@ class NutritionalPlanScreen extends StatelessWidget { onSelected: (value) { // Edit if (value == NutritionalPlanOptions.edit) { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.edit, - PlanForm(_nutritionalPlan), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.edit, + PlanForm(_nutritionalPlan), + ), ); // Delete diff --git a/lib/screens/nutritional_plans_screen.dart b/lib/screens/nutritional_plans_screen.dart index 3b9a258c6..278604e1e 100644 --- a/lib/screens/nutritional_plans_screen.dart +++ b/lib/screens/nutritional_plans_screen.dart @@ -20,8 +20,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:wger/providers/nutrition.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/app_drawer.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/nutrition/nutritional_plans_list.dart'; @@ -47,12 +47,14 @@ class _NutritionScreenState extends State { floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () async { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.newNutritionalPlan, - PlanForm(), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.newNutritionalPlan, + PlanForm(), + ), ); - //await showNutritionalPlanSheet(context, nutritionalPlan); }, ), body: Consumer( diff --git a/lib/screens/weight_screen.dart b/lib/screens/weight_screen.dart index 00d10f471..06cb9e801 100644 --- a/lib/screens/weight_screen.dart +++ b/lib/screens/weight_screen.dart @@ -18,8 +18,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/app_drawer.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/weight/entries_list.dart'; import 'package:wger/widgets/weight/forms.dart'; @@ -45,23 +45,17 @@ class _WeightScreenState extends State { floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () async { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.newEntry, - WeightForm(), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.newEntry, + WeightForm(), + ), ); }, ), body: WeightEntriesList(), ); } - - showWeightEntrySheet(BuildContext context) async { - showModalBottomSheet( - context: context, - builder: (BuildContext ctx) { - return WeightForm(); - }, - ); - } } diff --git a/lib/screens/workout_plan_screen.dart b/lib/screens/workout_plan_screen.dart index b0037215c..4b03f1b3d 100644 --- a/lib/screens/workout_plan_screen.dart +++ b/lib/screens/workout_plan_screen.dart @@ -21,8 +21,8 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/providers/workout_plans.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/workout_plans_screen.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/workouts/forms.dart'; import 'package:wger/widgets/workouts/workout_logs.dart'; import 'package:wger/widgets/workouts/workout_plan_detail.dart'; @@ -94,10 +94,13 @@ class _WorkoutPlanScreenState extends State { onSelected: (value) { // Edit if (value == WorkoutOptions.edit) { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.edit, - WorkoutForm(workoutPlan), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.edit, + WorkoutForm(workoutPlan), + ), ); // Delete diff --git a/lib/screens/workout_plans_screen.dart b/lib/screens/workout_plans_screen.dart index 630b4a12a..b7ee37279 100644 --- a/lib/screens/workout_plans_screen.dart +++ b/lib/screens/workout_plans_screen.dart @@ -22,8 +22,8 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/providers/workout_plans.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/app_drawer.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/workouts/forms.dart'; import 'package:wger/widgets/workouts/workout_plans_list.dart'; @@ -44,10 +44,13 @@ class _WorkoutPlansScreenState extends State { floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.newWorkout, - WorkoutForm(WorkoutPlan(creationDate: DateTime.now(), description: '')), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.newWorkout, + WorkoutForm(WorkoutPlan(creationDate: DateTime.now(), description: '')), + ), ); }, ), diff --git a/lib/widgets/core/bottom_sheet.dart b/lib/widgets/core/bottom_sheet.dart deleted file mode 100644 index 4481e9165..000000000 --- a/lib/widgets/core/bottom_sheet.dart +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (C) 2020 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * wger Workout Manager is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -import 'package:flutter/material.dart'; - -Future showFormBottomSheet(BuildContext context, String header, Widget form, - {bool scrollControlled: false}) async { - return showModalBottomSheet( - isScrollControlled: scrollControlled, - context: context, - builder: (BuildContext ctx) { - return Column( - children: [ - Icon( - Icons.remove, - color: Colors.grey, - ), - Text( - header, - style: Theme.of(ctx).textTheme.headline6, - ), - SizedBox(height: 10), - Divider(), - Container( - margin: EdgeInsets.symmetric(horizontal: 20), - child: form, - ) - ], - ); - }); -} diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 029f98768..788772ca8 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -26,10 +26,10 @@ import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/workout_plans.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/screens/workout_plan_screen.dart'; import 'package:wger/theme/theme.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/nutrition/charts.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/weight/charts.dart'; @@ -207,10 +207,13 @@ class _DashboardWeightWidgetState extends State { TextButton( child: Text(AppLocalizations.of(context)!.newEntry), onPressed: () async { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.newEntry, - WeightForm(), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.newEntry, + WeightForm(), + ), ); }, ), @@ -347,10 +350,13 @@ class NothingFound extends StatelessWidget { color: wgerPrimaryButtonColor, ), onPressed: () async { - showFormBottomSheet( + Navigator.pushNamed( context, - _titleForm, - _form, + FormScreen.routeName, + arguments: FormScreenArguments( + _titleForm, + _form, + ), ); }, ), diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index 46287845e..a35e32715 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -23,8 +23,8 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/providers/nutrition.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/theme/theme.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -72,11 +72,14 @@ class _MealWidgetState extends State { OutlinedButton( child: Text(AppLocalizations.of(context)!.addIngredient), onPressed: () { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.addIngredient, - MealItemForm(widget._meal), - scrollControlled: true, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.addIngredient, + MealItemForm(widget._meal), + true, + ), ); }, ), @@ -170,10 +173,13 @@ class DismissibleMealHeader extends StatelessWidget { Widget build(BuildContext context) { return InkWell( onLongPress: () { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.edit, - MealForm(_meal.planId, _meal), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.edit, + MealForm(_meal.planId, _meal), + ), ); }, child: Dismissible( diff --git a/lib/widgets/nutrition/nutritional_plan_detail.dart b/lib/widgets/nutrition/nutritional_plan_detail.dart index 39c9be0f4..b1e2a62c8 100644 --- a/lib/widgets/nutrition/nutritional_plan_detail.dart +++ b/lib/widgets/nutrition/nutritional_plan_detail.dart @@ -21,7 +21,7 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/models/nutrition/nutritrional_values.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/nutrition/charts.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/nutrition/meal.dart'; @@ -44,10 +44,13 @@ class NutritionalPlanDetailWidget extends StatelessWidget { child: ElevatedButton( child: Text(AppLocalizations.of(context)!.addMeal), onPressed: () { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.addMeal, - MealForm(_nutritionalPlan.id!), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.addMeal, + MealForm(_nutritionalPlan.id!), + ), ); }, ), diff --git a/lib/widgets/weight/entries_list.dart b/lib/widgets/weight/entries_list.dart index ed8f0ee12..70fa1929d 100644 --- a/lib/widgets/weight/entries_list.dart +++ b/lib/widgets/weight/entries_list.dart @@ -21,7 +21,7 @@ import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:wger/providers/body_weight.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/weight/charts.dart'; import 'package:wger/widgets/weight/forms.dart'; @@ -65,10 +65,13 @@ class WeightEntriesList extends StatelessWidget { confirmDismiss: (direction) async { // Edit entry if (direction == DismissDirection.startToEnd) { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.edit, - WeightForm(currentEntry), + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.edit, + WeightForm(currentEntry), + ), ); return false; } diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index f0c9cf611..411cd4aec 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -24,9 +24,9 @@ import 'package:wger/models/workouts/day.dart'; import 'package:wger/models/workouts/set.dart'; import 'package:wger/models/workouts/setting.dart'; import 'package:wger/providers/workout_plans.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/gym_mode.dart'; import 'package:wger/theme/theme.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/workouts/forms.dart'; class SettingWidget extends StatelessWidget { @@ -153,11 +153,14 @@ class _WorkoutDayWidgetState extends State { OutlinedButton( child: Text(AppLocalizations.of(context)!.addExercise), onPressed: () { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.newSet, - SetFormWidget(widget._day), - scrollControlled: true, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.newSet, + SetFormWidget(widget._day), + true, + ), ); }, ), diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index c80f2a122..8fcf63835 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -58,7 +58,7 @@ class WorkoutForm extends StatelessWidget { const minLength = 5; const maxLength = 100; if (value!.isEmpty || value.length < minLength || value.length > maxLength) { - return 'Please enter between $minLength and $maxLength characters.'; + return AppLocalizations.of(context)!.enterCharacters(minLength, maxLength); } return null; }, @@ -247,170 +247,157 @@ class _SetFormWidgetState extends State { @override Widget build(BuildContext context) { - return Container( - child: Form( - key: _formKey, - child: Column( - children: [ - TypeAheadFormField( - textFieldConfiguration: TextFieldConfiguration( - controller: this._exercisesController, - decoration: InputDecoration( - labelText: AppLocalizations.of(context)!.exercise, - helperMaxLines: 3, - helperText: 'You can search for more than one exercise, they will be grouped ' - 'together for a superset.'), - ), - suggestionsCallback: (pattern) async { - return await Provider.of(context, listen: false).searchExercise(pattern); - }, - itemBuilder: (context, suggestion) { - final result = suggestion! as Map; + return Form( + key: _formKey, + child: ListView( + children: [ + TypeAheadFormField( + textFieldConfiguration: TextFieldConfiguration( + controller: this._exercisesController, + decoration: InputDecoration( + labelText: AppLocalizations.of(context)!.exercise, + helperMaxLines: 3, + helperText: 'You can search for more than one exercise, they will be grouped ' + 'together for a superset.'), + ), + suggestionsCallback: (pattern) async { + return await Provider.of(context, listen: false).searchExercise(pattern); + }, + itemBuilder: (context, suggestion) { + final result = suggestion! as Map; - String serverUrl = Provider.of(context, listen: false).serverUrl!; - final exercise = - Provider.of(context, listen: false).findById(result['data']['id']); - return ListTile( - leading: Container( - width: 45, - child: result['data']['image'] != null - ? ExerciseImage( - imageUrl: result['data']['image'], - serverUrl: serverUrl, - ) - : Container(), - ), - title: Text(exercise.name), - subtitle: Text(exercise.categoryObj.name), - ); - }, - transitionBuilder: (context, suggestionsBox, controller) { - return suggestionsBox; - }, - onSuggestionSelected: (suggestion) { - final result = suggestion! as Map; - final exercise = - Provider.of(context, listen: false).findById(result['data']['id']); - addExercise(exercise); - }, - validator: (value) { - if (value!.isEmpty) { - return 'Please select an exercise'; + String serverUrl = Provider.of(context, listen: false).serverUrl!; + final exercise = + Provider.of(context, listen: false).findById(result['data']['id']); + return ListTile( + leading: Container( + width: 45, + child: result['data']['image'] != null + ? ExerciseImage( + imageUrl: result['data']['image'], + serverUrl: serverUrl, + ) + : Container(), + ), + title: Text(exercise.name), + subtitle: Text(exercise.categoryObj.name), + ); + }, + transitionBuilder: (context, suggestionsBox, controller) { + return suggestionsBox; + }, + onSuggestionSelected: (suggestion) { + final result = suggestion! as Map; + final exercise = + Provider.of(context, listen: false).findById(result['data']['id']); + addExercise(exercise); + this._exercisesController.text = ''; + }, + validator: (value) { + if (value!.isEmpty) { + return 'Please select an exercise'; + } + return null; + }, + ), + SizedBox(height: 10), + Text('Number of sets: ${_currentSetSliderValue.round()}'), + Slider( + value: _currentSetSliderValue, + min: 1, + max: 10, + divisions: 10, + label: _currentSetSliderValue.round().toString(), + onChanged: (double value) { + setState(() { + widget._set.sets = value.round(); + + // Add all settings to list + widget._set.settings = []; + for (var exercise in widget._set.exercisesObj) { + for (int loop = 0; loop < widget._set.sets; loop++) { + Setting setting = Setting.empty(); + setting.exerciseObj = exercise; + widget._set.settings.add(setting); + } } - return null; - }, - ), - SizedBox(height: 10), - Text('Number of sets: ${_currentSetSliderValue.round()}'), - Slider( - value: _currentSetSliderValue, - min: 1, - max: 10, - divisions: 10, - label: _currentSetSliderValue.round().toString(), - onChanged: (double value) { - setState(() { - widget._set.sets = value.round(); + _currentSetSliderValue = value; + }); + }, + ), + SwitchListTile( + title: Text('More details'), + value: _detailed, + onChanged: (value) { + setState(() { + _detailed = !_detailed; + }); + }, + ), + Text('If you do the same repetitions for all sets you can just enter ' + 'one value: e.g. for 4 sets just enter one "10" for the repetitions, ' + 'this automatically becomes "4 x 10".'), + ...widget._set.exercisesObj.map((exercise) { + final settings = + widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); - // Add all settings to list - widget._set.settings = []; - for (var exercise in widget._set.exercisesObj) { - for (int loop = 0; loop < widget._set.sets; loop++) { - /* - Setting setting = Setting(); - setting.exerciseObj = exercise; - widget._set.settings.add(setting); + return ExerciseSetting( + exercise, + settings, + _detailed, + _currentSetSliderValue, + removeExercise, + ); + }).toList(), + ElevatedButton( + child: Text(AppLocalizations.of(context)!.save), + onPressed: () async { + final isValid = _formKey.currentState!.validate(); + if (!isValid) { + return; + } + _formKey.currentState!.save(); - */ - } - } + final workoutProvider = Provider.of(context, listen: false); - _currentSetSliderValue = value; - }); - }, - ), - SwitchListTile( - title: Text('More details'), - value: _detailed, - onChanged: (value) { - setState(() { - _detailed = !_detailed; - }); - }, - ), - Text('If you do the same repetitions for all sets you can just enter ' - 'one value: e.g. for 4 sets just enter one "10" for the repetitions, ' - 'this automatically becomes "4 x 10".'), - SizedBox( - height: 350, - child: ListView( - children: [ - ...widget._set.exercisesObj.map((exercise) { - final settings = - widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); + // Save set + Set setDb = await workoutProvider.addSet(widget._set); + widget._set.id = setDb.id; - return ExerciseSetting( - exercise, - settings, - _detailed, - _currentSetSliderValue, - removeExercise, - ); - }).toList(), - ], - ), - ), - ElevatedButton( - child: Text(AppLocalizations.of(context)!.save), - onPressed: () async { - final isValid = _formKey.currentState!.validate(); - if (!isValid) { - return; - } - _formKey.currentState!.save(); + // Remove unused settings + widget._set.settings.removeWhere((s) => s.weight == null && s.reps == null); - final workoutProvider = Provider.of(context, listen: false); + // Save remaining settings + for (var setting in widget._set.settings) { + setting.setId = setDb.id!; - // Save set - Set setDb = await workoutProvider.addSet(widget._set); - widget._set.id = setDb.id; + setting.weightUnitId = workoutProvider.defaultWeightUnit.id; + setting.repetitionUnitId = workoutProvider.defaultRepetitionUnit.id; + setting.comment = ''; + setting.repsText = 'temp text'; - // Remove unused settings - widget._set.settings.removeWhere((s) => s.weight == null && s.reps == null); + Setting settingDb = await workoutProvider.addSetting(setting); + setting.id = settingDb.id; + } - // Save remaining settings - for (var setting in widget._set.settings) { - setting.setId = setDb.id!; + // Add to workout day + widget._day.sets.add(widget._set); - setting.weightUnitId = workoutProvider.defaultWeightUnit.id; - //setting.weightUnitId ?? workoutProvider.defaultWeightUnit.id; - setting.repetitionUnitId = workoutProvider.defaultRepetitionUnit.id; - //setting.repetitionUnitId ?? workoutProvider.defaultRepetitionUnit.id; - setting.comment = ''; - setting.repsText = 'temp text'; - - Setting settingDb = await workoutProvider.addSetting(setting); - setting.id = settingDb.id; - } - - // Add to workout day - widget._day.sets.add(widget._set); - - // Close the bottom sheet - Navigator.of(context).pop(); - }), - ], - ), + // Close the bottom sheet + Navigator.of(context).pop(); + }, + ), + ], ), ); } } class ExerciseSetting extends StatelessWidget { - Exercise _exercise; + final Exercise _exercise; int _numberOfSets = 4; bool _detailed; - Function removeExercise; + final Function removeExercise; List _settings = []; ExerciseSetting( @@ -451,7 +438,7 @@ class ExerciseSetting extends StatelessWidget { Widget build(BuildContext context) { return Column( children: [ - SizedBox(height: 15), + SizedBox(height: 20), Text(_exercise.name, style: TextStyle(fontWeight: FontWeight.bold)), IconButton( icon: Icon(Icons.close), @@ -460,7 +447,6 @@ class ExerciseSetting extends StatelessWidget { }, ), //ExerciseImage(imageUrl: _exercise.images.first.url), - Divider(), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ diff --git a/lib/widgets/workouts/workout_plan_detail.dart b/lib/widgets/workouts/workout_plan_detail.dart index 19abce7cd..205eb4180 100644 --- a/lib/widgets/workouts/workout_plan_detail.dart +++ b/lib/widgets/workouts/workout_plan_detail.dart @@ -19,8 +19,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:wger/models/workouts/workout_plan.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/workout_plan_screen.dart'; -import 'package:wger/widgets/core/bottom_sheet.dart'; import 'package:wger/widgets/workouts/day.dart'; import 'package:wger/widgets/workouts/forms.dart'; @@ -59,11 +59,13 @@ class _WorkoutPlanDetailState extends State { ElevatedButton( child: Text(AppLocalizations.of(context)!.add), onPressed: () { - showFormBottomSheet( + Navigator.pushNamed( context, - AppLocalizations.of(context)!.newDay, - DayFormWidget(widget._workoutPlan), - scrollControlled: true, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.newDay, + DayFormWidget(widget._workoutPlan), + ), ); }, ), diff --git a/test/nutritional_plans_screen_test.dart b/test/nutritional_plans_screen_test.dart index 10c8ffee8..3cddf8500 100644 --- a/test/nutritional_plans_screen_test.dart +++ b/test/nutritional_plans_screen_test.dart @@ -24,6 +24,7 @@ import 'package:mockito/mockito.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/providers/nutrition.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/nutritional_plans_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -52,6 +53,9 @@ void main() { localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: NutritionScreen(), + routes: { + FormScreen.routeName: (ctx) => FormScreen(), + }, ), ); } diff --git a/test/weight_screen_test.dart b/test/weight_screen_test.dart index de1dbafc9..5dc34f27e 100644 --- a/test/weight_screen_test.dart +++ b/test/weight_screen_test.dart @@ -24,6 +24,7 @@ import 'package:mockito/mockito.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/providers/body_weight.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/weight_screen.dart'; import 'package:wger/widgets/weight/charts.dart'; import 'package:wger/widgets/weight/forms.dart'; @@ -59,6 +60,9 @@ void main() { localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: WeightScreen(), + routes: { + FormScreen.routeName: (ctx) => FormScreen(), + }, ), ); } diff --git a/test/workout_plans_screen_test.dart b/test/workout_plans_screen_test.dart index 5975fecbd..806bc3753 100644 --- a/test/workout_plans_screen_test.dart +++ b/test/workout_plans_screen_test.dart @@ -24,6 +24,7 @@ import 'package:mockito/mockito.dart'; import 'package:provider/provider.dart'; import 'package:wger/models/workouts/workout_plan.dart'; import 'package:wger/providers/workout_plans.dart'; +import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/workout_plans_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import 'package:wger/widgets/workouts/forms.dart'; @@ -54,6 +55,9 @@ void main() { localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: WorkoutPlansScreen(), + routes: { + FormScreen.routeName: (ctx) => FormScreen(), + }, ), ); } From ba0fa896e1b534458c30234b0c8a353b5c0f01fa Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 2 Apr 2021 18:00:35 +0200 Subject: [PATCH 55/58] Remove hard coded strings from forms --- lib/l10n/app_en.arb | 14 ++++++++++++++ lib/widgets/workouts/forms.dart | 25 +++++++++++-------------- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c60a179a3..99bea11de 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -97,6 +97,7 @@ "@rir": { "description": "Shorthand for Repetitions In Reserve" }, + "sameRepetitions": "If you do the same repetitions for all sets you can just fill in one value: e.g. for 4 sets just enter one \"10\" for the repetitions, this automatically becomes \"4 x 10\".", "comment": "Comment", "@comment": { "description": "Comment, additional information" @@ -119,6 +120,7 @@ "@newSet": { "description": "Header when adding a new set to a workout day" }, + "selectExercises": "You can search for more than one exercise, they will be grouped together for a superset.", "gymMode": "Gym mode", "@gymMode": { "description": "Label when starting the gym mode" @@ -260,6 +262,10 @@ "@enterValue": { "description": "Error message when the user hasn't entered a value on a required field" }, + "selectExercise": "Please select an exercise", + "@selectExercise": { + "description": "Error message when the user hasn't selected an exercise in the form" + }, "enterCharacters": "Please enter between {min} and {max} characters", "@enterCharacters": { "description": "Error message when the user hasn't entered the correct number of characters in a form", @@ -269,6 +275,14 @@ "max": {} } }, + "nrOfSets": "Number of sets: {nrOfSets}", + "@nrOfSets": { + "description": "Label shown on the slider where the user selects the nr of sets", + "type": "text", + "placeholders": { + "nrOfSets": {} + } + }, "enterValidNumber": "Please enter a valid number", "@enterValidNumber": { "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index 8fcf63835..e9efd52fa 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -160,7 +160,7 @@ class _DayFormWidgetState extends State { const minLength = 5; const maxLength = 100; if (value!.isEmpty || value.length < minLength || value.length > maxLength) { - return 'Please enter between $minLength and $maxLength characters.'; + return AppLocalizations.of(context)!.enterCharacters(minLength, maxLength); } return null; }, @@ -257,8 +257,7 @@ class _SetFormWidgetState extends State { decoration: InputDecoration( labelText: AppLocalizations.of(context)!.exercise, helperMaxLines: 3, - helperText: 'You can search for more than one exercise, they will be grouped ' - 'together for a superset.'), + helperText: AppLocalizations.of(context)!.selectExercises), ), suggestionsCallback: (pattern) async { return await Provider.of(context, listen: false).searchExercise(pattern); @@ -295,13 +294,13 @@ class _SetFormWidgetState extends State { }, validator: (value) { if (value!.isEmpty) { - return 'Please select an exercise'; + return AppLocalizations.of(context)!.selectExercise; } return null; }, ), SizedBox(height: 10), - Text('Number of sets: ${_currentSetSliderValue.round()}'), + Text(AppLocalizations.of(context)!.nrOfSets(_currentSetSliderValue.round())), Slider( value: _currentSetSliderValue, min: 1, @@ -326,7 +325,7 @@ class _SetFormWidgetState extends State { }, ), SwitchListTile( - title: Text('More details'), + title: Text(AppLocalizations.of(context)!.toggleDetails), value: _detailed, onChanged: (value) { setState(() { @@ -334,9 +333,7 @@ class _SetFormWidgetState extends State { }); }, ), - Text('If you do the same repetitions for all sets you can just enter ' - 'one value: e.g. for 4 sets just enter one "10" for the repetitions, ' - 'this automatically becomes "4 x 10".'), + Text(AppLocalizations.of(context)!.sameRepetitions), ...widget._set.exercisesObj.map((exercise) { final settings = widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); @@ -450,11 +447,11 @@ class ExerciseSetting extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - Text('Reps'), - if (_detailed) Text('Unit'), - Text('Weight'), - if (_detailed) Text('Weight unit'), - if (_detailed) Text('RiR'), + Text(AppLocalizations.of(context)!.repetitions), + if (_detailed) Text(AppLocalizations.of(context)!.unit), + Text(AppLocalizations.of(context)!.weight), + if (_detailed) Text(AppLocalizations.of(context)!.unit), + if (_detailed) Text(AppLocalizations.of(context)!.rir), ], ), getRow(), From 110579aeb7bb3061bd834bb24865523f7e0721a9 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 2 Apr 2021 21:01:47 +0200 Subject: [PATCH 56/58] Some cleanup work on exercise images --- lib/models/exercises/exercise.dart | 8 +- lib/models/exercises/image.dart | 12 +++ lib/models/exercises/image.g.dart | 8 +- lib/providers/exercises.dart | 8 +- lib/providers/workout_plans.dart | 114 ---------------------------- lib/widgets/workouts/day.dart | 12 +-- lib/widgets/workouts/exercises.dart | 15 ++-- lib/widgets/workouts/forms.dart | 34 ++++----- 8 files changed, 56 insertions(+), 155 deletions(-) diff --git a/lib/models/exercises/exercise.dart b/lib/models/exercises/exercise.dart index 1bda09ddc..e47686e19 100644 --- a/lib/models/exercises/exercise.dart +++ b/lib/models/exercises/exercise.dart @@ -83,8 +83,12 @@ class Exercise { this.muscles = muscles ?? []; } - ExerciseImage get getMainImage { - return images.firstWhere((image) => image.isMain); + ExerciseImage? get getMainImage { + try { + return images.firstWhere((image) => image.isMain); + } on StateError catch (e) { + return null; + } } // Boilerplate diff --git a/lib/models/exercises/image.dart b/lib/models/exercises/image.dart index 227c6614f..c57b4a26e 100644 --- a/lib/models/exercises/image.dart +++ b/lib/models/exercises/image.dart @@ -22,6 +22,15 @@ part 'image.g.dart'; @JsonSerializable() class ExerciseImage { + @JsonKey(required: true) + final int id; + + @JsonKey(required: true) + final String uuid; + + @JsonKey(required: true, name: 'exercise') + final int exerciseId; + @JsonKey(required: true, name: 'image') final String url; @@ -29,6 +38,9 @@ class ExerciseImage { final bool isMain; ExerciseImage({ + required this.id, + required this.uuid, + required this.exerciseId, required this.url, required this.isMain, }); diff --git a/lib/models/exercises/image.g.dart b/lib/models/exercises/image.g.dart index 320f883e3..40caffdb2 100644 --- a/lib/models/exercises/image.g.dart +++ b/lib/models/exercises/image.g.dart @@ -7,8 +7,11 @@ part of 'image.dart'; // ************************************************************************** ExerciseImage _$ExerciseImageFromJson(Map json) { - $checkKeys(json, requiredKeys: const ['image']); + $checkKeys(json, requiredKeys: const ['id', 'uuid', 'exercise', 'image']); return ExerciseImage( + id: json['id'] as int, + uuid: json['uuid'] as String, + exerciseId: json['exercise'] as int, url: json['image'] as String, isMain: json['is_main'] as bool? ?? false, ); @@ -16,6 +19,9 @@ ExerciseImage _$ExerciseImageFromJson(Map json) { Map _$ExerciseImageToJson(ExerciseImage instance) => { + 'id': instance.id, + 'uuid': instance.uuid, + 'exercise': instance.exerciseId, 'image': instance.url, 'is_main': instance.isMain, }; diff --git a/lib/providers/exercises.dart b/lib/providers/exercises.dart index 372a52f98..e042f10e9 100644 --- a/lib/providers/exercises.dart +++ b/lib/providers/exercises.dart @@ -22,6 +22,7 @@ import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; +import 'package:json_annotation/json_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/models/exercises/category.dart'; import 'package:wger/models/exercises/equipment.dart'; @@ -120,11 +121,11 @@ class Exercises extends WgerBaseProvider with ChangeNotifier { _exercisesUrlPath, query: {'limit': '1000'}, )); - final extractedData = json.decode(response.body) as Map; + final exercisesData = json.decode(response.body) as Map; try { // Load exercises - extractedData['results'].forEach((e) => _exercises.add(Exercise.fromJson(e))); + exercisesData['results'].forEach((e) => _exercises.add(Exercise.fromJson(e))); // Save the result to the cache final exerciseData = { @@ -138,7 +139,8 @@ class Exercises extends WgerBaseProvider with ChangeNotifier { prefs.setString('exerciseData', json.encode(exerciseData)); notifyListeners(); - } catch (error) { + } on MissingRequiredKeysException catch (error) { + log(error.missingKeys.toString()); throw (error); } } diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index 43857d5ec..e663fb1b2 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -24,7 +24,6 @@ import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/models/exercises/exercise.dart'; -import 'package:wger/models/exercises/image.dart'; import 'package:wger/models/http_exception.dart'; import 'package:wger/models/workouts/day.dart'; import 'package:wger/models/workouts/log.dart'; @@ -195,119 +194,6 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier { notifyListeners(); } - // TODO: delete - Future setAllFullWorkouts() async { - for (var plan in _workoutPlans) { - setFullWorkout(plan.id!); - } - } - - // TODO: delete - Future setFullWorkout(int workoutId) async { - final data = await fetch(makeUrl( - _workoutPlansUrlPath, - id: workoutId, - objectMethod: 'canonical_representation', - )); - - //try { - WorkoutPlan workout = _workoutPlans.firstWhere((element) => element.id == workoutId); - - List days = []; - for (final entry in data['day_list']) { - List sets = []; - List settingsComputed = []; - - for (final set in entry['set_list']) { - List settings = []; - List exercises = []; - - for (final exerciseData in set['exercise_list']) { - List images = []; - - for (final image in exerciseData['image_list']) { - images.add( - ExerciseImage( - url: auth.serverUrl! + image["image"], - isMain: image['is_main'], - ), - ); - } - - //TODO: read exercise data from cache from Exercises provider - Exercise exercise = Exercise( - id: exerciseData['obj']['id'], - uuid: exerciseData['obj']['uuid'], - creationDate: DateTime.parse(exerciseData['obj']['creation_date']), - name: exerciseData['obj']['name'], - description: exerciseData['obj']['description'], - categoryId: exerciseData['obj']['category'], - images: images, - ); - exercises.add(exercise); - - // Settings - if (exerciseData['setting_obj_list'].length > 0) { - settings.add( - Setting.withData( - id: exerciseData['setting_obj_list'][0]['id'], - setId: exerciseData['setting_obj_list'][0]['set'], - comment: exerciseData['setting_obj_list'][0]['comment'], - reps: exerciseData['setting_obj_list'][0]['reps'], - weight: 10, - repetitionUnitId: DEFAULT_REPETITION_UNIT, - weightUnitId: DEFAULT_WEIGHT_UNIT, - //weight: setting['setting_obj_list'][0]['weight'] == null - // ? '' - // : setting['setting_obj_list'][0]['weight'], - repsText: exerciseData['setting_text'], - exerciseObj: exercise, - ), - ); - } - } - - // Computed settings - for (var setting in set['settings_computed']) { - settingsComputed.add(Setting.fromJson(setting)); - } - - // Sets - sets.add(Set.withData( - id: set['obj']['id'], - sets: set['obj']['sets'], - order: set['obj']['order'], - settings: settings, - settingsComputed: settingsComputed, - exercises: exercises, - )); - } - - // Days - days.add(Day.withData( - id: entry['obj']['id'], - workoutId: workoutId, - description: entry['obj']['description'], - sets: sets, - daysOfWeek: [1, 3] - //daysOfWeek: entry['obj']['day'], - )); - } - workout.days = days; - - // Logs - final logData = await fetch(makeUrl(_logsUrlPath, query: {'workout': workoutId.toString()})); - for (final entry in logData['results']) { - workout.logs.add(Log.fromJson(entry)); - } - notifyListeners(); - - return workout; - //} catch (error) { - // throw (error); - //} - } - Future postWorkout(WorkoutPlan workout) async { final data = await post(workout.toJson(), makeUrl(_workoutPlansUrlPath)); final plan = WorkoutPlan.fromJson(data); diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 411cd4aec..29f8a383d 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -27,6 +27,7 @@ import 'package:wger/providers/workout_plans.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/gym_mode.dart'; import 'package:wger/theme/theme.dart'; +import 'package:wger/widgets/workouts/exercises.dart'; import 'package:wger/widgets/workouts/forms.dart'; class SettingWidget extends StatelessWidget { @@ -40,16 +41,7 @@ class SettingWidget extends StatelessWidget { Widget build(BuildContext context) { return ListTile( leading: Container( - child: setting.exerciseObj.images.length > 0 - ? FadeInImage( - placeholder: AssetImage('assets/images/placeholder.png'), - image: NetworkImage(setting.exerciseObj.getMainImage.url), - fit: BoxFit.cover, - ) - : Image( - image: AssetImage('assets/images/placeholder.png'), - color: Color.fromRGBO(255, 255, 255, 0.3), - colorBlendMode: BlendMode.modulate), + child: ExerciseImageWidget(image: setting.exerciseObj.getMainImage), width: 45, ), title: Text(setting.exerciseObj.name), diff --git a/lib/widgets/workouts/exercises.dart b/lib/widgets/workouts/exercises.dart index c6758e7cd..fbc075ca2 100644 --- a/lib/widgets/workouts/exercises.dart +++ b/lib/widgets/workouts/exercises.dart @@ -17,22 +17,21 @@ */ import 'package:flutter/material.dart'; +import 'package:wger/models/exercises/image.dart'; -class ExerciseImage extends StatelessWidget { - const ExerciseImage({ - required this.imageUrl, - required this.serverUrl, +class ExerciseImageWidget extends StatelessWidget { + const ExerciseImageWidget({ + this.image, }); - final String imageUrl; - final String serverUrl; + final ExerciseImage? image; @override Widget build(BuildContext context) { - return imageUrl != null + return image != null ? FadeInImage( placeholder: AssetImage('assets/images/placeholder.png'), - image: NetworkImage(serverUrl + imageUrl), + image: NetworkImage(image!.url), fit: BoxFit.cover, ) : Image( diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index e9efd52fa..a51b6eb08 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -242,9 +242,22 @@ class _SetFormWidgetState extends State { void addExercise(Exercise exercise) { setState(() { widget._set.addExercise(exercise); + addSettings(); }); } + /// Adds settings to the set + void addSettings() { + widget._set.settings = []; + for (var exercise in widget._set.exercisesObj) { + for (int loop = 0; loop < widget._set.sets; loop++) { + Setting setting = Setting.empty(); + setting.exerciseObj = exercise; + widget._set.settings.add(setting); + } + } + } + @override Widget build(BuildContext context) { return Form( @@ -271,15 +284,11 @@ class _SetFormWidgetState extends State { return ListTile( leading: Container( width: 45, - child: result['data']['image'] != null - ? ExerciseImage( - imageUrl: result['data']['image'], - serverUrl: serverUrl, - ) - : Container(), + child: ExerciseImageWidget(image: exercise.getMainImage), ), title: Text(exercise.name), - subtitle: Text(exercise.categoryObj.name), + subtitle: Text( + '${exercise.categoryObj.name} / ${exercise.equipment.map((e) => e.name).join(', ')}'), ); }, transitionBuilder: (context, suggestionsBox, controller) { @@ -310,17 +319,8 @@ class _SetFormWidgetState extends State { onChanged: (double value) { setState(() { widget._set.sets = value.round(); - - // Add all settings to list - widget._set.settings = []; - for (var exercise in widget._set.exercisesObj) { - for (int loop = 0; loop < widget._set.sets; loop++) { - Setting setting = Setting.empty(); - setting.exerciseObj = exercise; - widget._set.settings.add(setting); - } - } _currentSetSliderValue = value; + addSettings(); }); }, ), From e7c8b4cf3c75db8d29acde1b7e366f86c0e62b9e Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 1 Apr 2021 18:37:05 +0000 Subject: [PATCH 57/58] Translated using Weblate (German) Currently translated at 100.0% (84 of 84 strings) Translation: wger Workout Manager/Mobile App Translate-URL: https://hosted.weblate.org/projects/wger/mobile/de/ --- lib/l10n/app_de.arb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 738f392f7..46773f9a4 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -253,5 +253,25 @@ "login": "Anmelden", "@login": { "description": "Text for login button" + }, + "addExercise": "Diesem Tag eine Übung hinzufügen", + "@addExercise": {}, + "confirmDelete": "Sind Sie sicher, dass Sie \"{toDelete}\" löschen möchten?", + "@confirmDelete": { + "description": "Confirmation text before the user deletes an object", + "type": "text", + "placeholders": { + "toDelete": {} + } + }, + "noNutritionalPlans": "Sie haben keine Ernährungspläne", + "@noNutritionalPlans": { + "description": "Message shown when the user has no nutritional plans" + }, + "todaysWorkout": "Ihr Training heute", + "@todaysWorkout": {}, + "noWorkoutPlans": "Sie haben keine Trainingspläne", + "@noWorkoutPlans": { + "description": "Message shown when the user has no workout plans" } } From 9e8d2e055ad5232925db33f8f1e54fdad0a0384c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sat, 3 Apr 2021 13:30:14 +0200 Subject: [PATCH 58/58] Polish the add set form --- lib/l10n/app_en.arb | 22 ++- lib/models/workouts/setting.dart | 51 +++--- lib/models/workouts/setting.g.dart | 5 +- lib/screens/form_screen.dart | 1 + lib/widgets/workouts/forms.dart | 266 ++++++++++++++++++----------- 5 files changed, 227 insertions(+), 118 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 99bea11de..dbe05122a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -93,11 +93,29 @@ "@repetitions": { "description": "Repetitions for an exercise set" }, + "reps": "Reps", + "@reps": { + "description": "Shorthand for repetitions, used when space constraints are tighter" + }, "rir": "RiR", "@rir": { "description": "Shorthand for Repetitions In Reserve" }, - "sameRepetitions": "If you do the same repetitions for all sets you can just fill in one value: e.g. for 4 sets just enter one \"10\" for the repetitions, this automatically becomes \"4 x 10\".", + "weightUnit": "Weight unit", + "repetitionUnit": "Repetition unit", + "set": "Set", + "@set": { + "description": "A set in a workout plan" + }, + "setNr": "Set {nr}", + "@setNr": { + "description": "Header in form indicating the number of the current set. Can also be translated as something like 'Set Nr. xy'.", + "type": "text", + "placeholders": { + "nr": {} + } + }, + "sameRepetitions": "If you do the same repetitions and weight for all sets you can just fill in one row. For example for 4 sets just enter one \"10\" for the repetitions, this automatically becomes \"4 x 10\".", "comment": "Comment", "@comment": { "description": "Comment, additional information" @@ -120,7 +138,7 @@ "@newSet": { "description": "Header when adding a new set to a workout day" }, - "selectExercises": "You can search for more than one exercise, they will be grouped together for a superset.", + "selectExercises": "If you want to do a superset you can search for several exercises, they will be grouped together", "gymMode": "Gym mode", "@gymMode": { "description": "Label when starting the gym mode" diff --git a/lib/models/workouts/setting.dart b/lib/models/workouts/setting.dart index 91709eed9..63d37ee72 100644 --- a/lib/models/workouts/setting.dart +++ b/lib/models/workouts/setting.dart @@ -8,12 +8,17 @@ part 'setting.g.dart'; @JsonSerializable() class Setting { + static final possibleValues = ['1', '1.5', '2', '2.5', '3', '3.5']; + @JsonKey(required: true) int? id; @JsonKey(required: true, name: 'set') late int setId; + @JsonKey(required: true) + late int order; + @JsonKey(ignore: true) late Exercise exerciseObj; @@ -27,10 +32,10 @@ class Setting { late RepetitionUnit repetitionUnitObj; @JsonKey(required: true) - late int reps; + int? reps; @JsonKey(required: true, fromJson: toNum, toJson: toString) - late num weight; + num? weight; @JsonKey(required: true, name: 'weight_unit') late int weightUnitId; @@ -51,6 +56,7 @@ class Setting { Setting({ this.id, required this.setId, + required this.order, required this.exerciseId, required this.repetitionUnitId, required this.reps, @@ -59,27 +65,32 @@ class Setting { required this.rir, }); - Setting.withData({ - this.id, - required this.setId, - Exercise? exerciseObj, - required this.repetitionUnitId, - required this.reps, - required this.weight, - required this.weightUnitId, - required this.comment, - this.rir = '', - required this.repsText, - }) { - if (exerciseObj != null) { - this.exerciseId = exerciseObj.id; - this.exerciseObj = exerciseObj; - } - } - Setting.empty(); // Boilerplate factory Setting.fromJson(Map json) => _$SettingFromJson(json); Map toJson() => _$SettingToJson(this); + + void setExercise(Exercise exercise) { + exerciseObj = exercise; + exerciseId = exercise.id; + } + + void setWeightUnit(WeightUnit weightUnit) { + weightUnitObj = weightUnit; + weightUnitId = weightUnit.id; + } + + void setRepetitionUnit(RepetitionUnit repetitionUnit) { + repetitionUnitObj = repetitionUnit; + repetitionUnitId = repetitionUnit.id; + } + + void setRir(String rir) { + if (possibleValues.contains(rir)) { + this.rir = rir; + } else { + throw Exception('RiR value not allowed'); + } + } } diff --git a/lib/models/workouts/setting.g.dart b/lib/models/workouts/setting.g.dart index 62be72439..464e6eaed 100644 --- a/lib/models/workouts/setting.g.dart +++ b/lib/models/workouts/setting.g.dart @@ -10,6 +10,7 @@ Setting _$SettingFromJson(Map json) { $checkKeys(json, requiredKeys: const [ 'id', 'set', + 'order', 'exercise', 'repetition_unit', 'reps', @@ -21,9 +22,10 @@ Setting _$SettingFromJson(Map json) { return Setting( id: json['id'] as int?, setId: json['set'] as int, + order: json['order'] as int, exerciseId: json['exercise'] as int, repetitionUnitId: json['repetition_unit'] as int, - reps: json['reps'] as int, + reps: json['reps'] as int?, weightUnitId: json['weight_unit'] as int, comment: json['comment'] as String, rir: json['rir'] as String?, @@ -33,6 +35,7 @@ Setting _$SettingFromJson(Map json) { Map _$SettingToJson(Setting instance) => { 'id': instance.id, 'set': instance.setId, + 'order': instance.order, 'exercise': instance.exerciseId, 'repetition_unit': instance.repetitionUnitId, 'reps': instance.reps, diff --git a/lib/screens/form_screen.dart b/lib/screens/form_screen.dart index 510af8730..dc9f70c71 100644 --- a/lib/screens/form_screen.dart +++ b/lib/screens/form_screen.dart @@ -41,6 +41,7 @@ class FormScreen extends StatelessWidget { ModalRoute.of(context)!.settings.arguments as FormScreenArguments; return Scaffold( + backgroundColor: Colors.white, appBar: AppBar(title: Text(args.title)), body: args.hasListView ? Padding( diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index a51b6eb08..b824b4033 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -215,7 +215,6 @@ class SetFormWidget extends StatefulWidget { late Set _set; SetFormWidget(Day this._day, [Set? set]) { - //this._day = day; this._set = set ?? Set.withData(day: _day.id, sets: 4); } @@ -249,10 +248,20 @@ class _SetFormWidgetState extends State { /// Adds settings to the set void addSettings() { widget._set.settings = []; + int order = 0; for (var exercise in widget._set.exercisesObj) { + order++; for (int loop = 0; loop < widget._set.sets; loop++) { Setting setting = Setting.empty(); - setting.exerciseObj = exercise; + setting.order = order; + setting.setExercise(exercise); + setting.setRepetitionUnit( + Provider.of(context, listen: false).defaultRepetitionUnit, + ); + setting.setWeightUnit( + Provider.of(context, listen: false).defaultWeightUnit, + ); + widget._set.settings.add(setting); } } @@ -302,14 +311,16 @@ class _SetFormWidgetState extends State { this._exercisesController.text = ''; }, validator: (value) { - if (value!.isEmpty) { + if (widget._set.exercisesIds.length == 0) { return AppLocalizations.of(context)!.selectExercise; } return null; }, ), SizedBox(height: 10), - Text(AppLocalizations.of(context)!.nrOfSets(_currentSetSliderValue.round())), + Center( + child: Text(AppLocalizations.of(context)!.nrOfSets(_currentSetSliderValue.round())), + ), Slider( value: _currentSetSliderValue, min: 1, @@ -333,7 +344,10 @@ class _SetFormWidgetState extends State { }); }, ), - Text(AppLocalizations.of(context)!.sameRepetitions), + Text( + AppLocalizations.of(context)!.sameRepetitions, + style: TextStyle(fontSize: 12, color: Colors.black54), + ), ...widget._set.exercisesObj.map((exercise) { final settings = widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); @@ -367,9 +381,6 @@ class _SetFormWidgetState extends State { // Save remaining settings for (var setting in widget._set.settings) { setting.setId = setDb.id!; - - setting.weightUnitId = workoutProvider.defaultWeightUnit.id; - setting.repetitionUnitId = workoutProvider.defaultRepetitionUnit.id; setting.comment = ''; setting.repsText = 'temp text'; @@ -407,23 +418,71 @@ class ExerciseSetting extends StatelessWidget { this._numberOfSets = sliderValue.round(); } - Widget getRow() { + Widget getRows(BuildContext context) { List out = []; for (var i = 0; i < _numberOfSets; i++) { var setting = _settings[i]; out.add( - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - RepsInputWidget(setting), - SizedBox(width: 4), - if (_detailed) WeightUnitInputWidget(key: Key(i.toString())), - WeightInputWidget(setting), - SizedBox(width: 4), - if (_detailed) RepetitionUnitInputWidget(), - if (_detailed) RiRInputWidget(), - ], - ), + _detailed + ? Column( + //crossAxisAlignment: CrossAxisAlignment.baseline, + //1textBaseline: TextBaseline.alphabetic, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + AppLocalizations.of(context)!.setNr(i + 1), + style: Theme.of(context).textTheme.headline6, + ), + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Flexible( + flex: 2, + child: RepsInputWidget(setting, _detailed), + ), + SizedBox(width: 4), + Flexible( + flex: 3, + child: WeightUnitInputWidget(setting, key: Key(i.toString())), + ), + ], + ), + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Flexible( + flex: 2, + child: WeightInputWidget(setting, _detailed), + ), + SizedBox(width: 4), + Flexible( + flex: 3, + child: RepetitionUnitInputWidget(setting), + ), + ], + ), + Flexible( + flex: 2, + child: RiRInputWidget(setting), + ), + SizedBox(height: 15), + ], + ) + : Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + AppLocalizations.of(context)!.setNr(i + 1), + style: TextStyle(fontWeight: FontWeight.bold), + ), + SizedBox(width: 10), + Flexible(child: RepsInputWidget(setting, _detailed)), + SizedBox(width: 4), + Flexible(child: WeightInputWidget(setting, _detailed)), + ], + ), ); } return Column( @@ -435,26 +494,27 @@ class ExerciseSetting extends StatelessWidget { Widget build(BuildContext context) { return Column( children: [ - SizedBox(height: 20), - Text(_exercise.name, style: TextStyle(fontWeight: FontWeight.bold)), + SizedBox(height: 30), + Text( + _exercise.name, + style: Theme.of(context).textTheme.headline6, + ), IconButton( - icon: Icon(Icons.close), + icon: Icon(Icons.delete_outline), onPressed: () { removeExercise(_exercise); }, ), //ExerciseImage(imageUrl: _exercise.images.first.url), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - Text(AppLocalizations.of(context)!.repetitions), - if (_detailed) Text(AppLocalizations.of(context)!.unit), - Text(AppLocalizations.of(context)!.weight), - if (_detailed) Text(AppLocalizations.of(context)!.unit), - if (_detailed) Text(AppLocalizations.of(context)!.rir), - ], - ), - getRow(), + if (!_detailed) + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Text(AppLocalizations.of(context)!.repetitions), + Text(AppLocalizations.of(context)!.weight), + ], + ), + getRows(context), ], ); } @@ -462,52 +522,77 @@ class ExerciseSetting extends StatelessWidget { class RepsInputWidget extends StatelessWidget { final _repsController = TextEditingController(); - Setting _setting; + final Setting _setting; + final bool _detailed; - RepsInputWidget(this._setting); + RepsInputWidget(this._setting, this._detailed); @override Widget build(BuildContext context) { - return Flexible( - child: TextFormField( - //decoration: InputDecoration(labelText: 'Reps'), - controller: _repsController, - keyboardType: TextInputType.number, - onSaved: (newValue) { - if (newValue != null && newValue != '') { - _setting.reps = int.parse(newValue); - } - }, + return TextFormField( + decoration: InputDecoration( + labelText: _detailed ? AppLocalizations.of(context)!.repetitions : '', + errorMaxLines: 2, ), + controller: _repsController, + keyboardType: TextInputType.number, + validator: (value) { + try { + if (value != "") { + double.parse(value!); + } + } catch (error) { + return AppLocalizations.of(context)!.enterValidNumber; + } + return null; + }, + onSaved: (newValue) { + if (newValue != null && newValue != '') { + _setting.reps = int.parse(newValue); + } + }, ); } } class WeightInputWidget extends StatelessWidget { final _weightController = TextEditingController(); - Setting _setting; + final Setting _setting; + final bool _detailed; - WeightInputWidget(this._setting); + WeightInputWidget(this._setting, this._detailed); @override Widget build(BuildContext context) { - return Flexible( - child: TextFormField( - //decoration: InputDecoration(labelText: 'Weight'), - controller: _weightController, - keyboardType: TextInputType.number, - onSaved: (newValue) { - if (newValue != null && newValue != '') { - _setting.weight = double.parse(newValue); - } - }, + return TextFormField( + decoration: InputDecoration( + labelText: _detailed ? AppLocalizations.of(context)!.weight : '', + errorMaxLines: 2, ), + controller: _weightController, + keyboardType: TextInputType.number, + validator: (value) { + try { + if (value != "") { + double.parse(value!); + } + } catch (error) { + return AppLocalizations.of(context)!.enterValidNumber; + } + return null; + }, + onSaved: (newValue) { + if (newValue != null && newValue != '') { + _setting.weight = double.parse(newValue); + } + }, ); } } class RiRInputWidget extends StatefulWidget { - RiRInputWidget(); + final Setting _setting; + RiRInputWidget(this._setting); @override _RiRInputWidgetState createState() => _RiRInputWidgetState(); @@ -518,19 +603,16 @@ class _RiRInputWidgetState extends State { @override Widget build(BuildContext context) { - return DropdownButton( + return DropdownButtonFormField( + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.rir), value: dropdownValue, - underline: Container( - height: 0, - //color: Colors.deepPurpleAccent, - ), onChanged: (String? newValue) { setState(() { dropdownValue = newValue!; + widget._setting.setRir(newValue); }); }, - items: ['1', '1.5', '2', '2.5', '3', '3.5'] - .map>((String value) { + items: Setting.possibleValues.map>((String value) { return DropdownMenuItem( value: value, child: Text(value), @@ -541,26 +623,26 @@ class _RiRInputWidgetState extends State { } class WeightUnitInputWidget extends StatefulWidget { - WeightUnitInputWidget({Key? key}) : super(key: key); + final Setting _setting; + + WeightUnitInputWidget(this._setting, {Key? key}) : super(key: key); @override _WeightUnitInputWidgetState createState() => _WeightUnitInputWidgetState(); } class _WeightUnitInputWidgetState extends State { - late WeightUnit dropdownValue; - @override Widget build(BuildContext context) { - return DropdownButton( - value: dropdownValue, - underline: Container( - height: 0, - // color: Colors.deepPurpleAccent, - ), + WeightUnit selectedWeightUnit = widget._setting.weightUnitObj; + + return DropdownButtonFormField( + value: selectedWeightUnit, + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.weightUnit), onChanged: (WeightUnit? newValue) { setState(() { - dropdownValue = newValue!; + selectedWeightUnit = newValue!; + widget._setting.setWeightUnit(newValue); }); }, items: Provider.of(context, listen: false) @@ -568,10 +650,7 @@ class _WeightUnitInputWidgetState extends State { .map>((WeightUnit value) { return DropdownMenuItem( value: value, - child: Text( - value.name, - style: TextStyle(fontSize: 12), - ), + child: Text(value.name), ); }).toList(), ); @@ -579,26 +658,26 @@ class _WeightUnitInputWidgetState extends State { } class RepetitionUnitInputWidget extends StatefulWidget { - RepetitionUnitInputWidget(); + final Setting _setting; + RepetitionUnitInputWidget(this._setting); @override _RepetitionUnitInputWidgetState createState() => _RepetitionUnitInputWidgetState(); } class _RepetitionUnitInputWidgetState extends State { - late RepetitionUnit dropdownValue; - @override Widget build(BuildContext context) { - return DropdownButton( - value: dropdownValue, - underline: Container( - height: 0, - // color: Colors.deepPurpleAccent, - ), + RepetitionUnit selectedWeightUnit = widget._setting.repetitionUnitObj; + + return DropdownButtonFormField( + value: selectedWeightUnit, + decoration: InputDecoration(labelText: AppLocalizations.of(context)!.repetitionUnit), + isDense: true, onChanged: (RepetitionUnit? newValue) { setState(() { - dropdownValue = newValue!; + selectedWeightUnit = newValue!; + widget._setting.setRepetitionUnit(newValue); }); }, items: Provider.of(context, listen: false) @@ -606,10 +685,7 @@ class _RepetitionUnitInputWidgetState extends State { .map>((RepetitionUnit value) { return DropdownMenuItem( value: value, - child: Text( - value.name, - style: TextStyle(fontSize: 12), - ), + child: Text(value.name), ); }).toList(), );