Merge branch 'master' into patch-1

This commit is contained in:
Allan Nordhøy
2021-04-06 16:34:59 +00:00
committed by GitHub
120 changed files with 3836 additions and 1852 deletions

View File

@@ -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
@@ -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:

View File

@@ -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)

View File

@@ -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 app stores.
@@ -16,15 +16,35 @@ Install Flutter, all its dependencies and create a new virtual device:
<https://flutter.dev/docs/get-started/install>
### 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 <http://localhost:8000/de/user/api-key>
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
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).
Generate translation files with ``flutter gen-l10n``
### 5
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
Translate the app to your language on [Hosted Weblate](https://hosted.weblate.org/engage/wger/).
## Contact
Feel free to get in touch if you found this useful or something didn't behave

View File

@@ -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]

View File

@@ -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")

View File

@@ -24,6 +24,11 @@ fastlane playstore
----
## Android
### android updateclosed_alpha
```
fastlane android updateclosed_alpha
```
Upload closed alpha app and update store entry
### android test
```
fastlane android test

View File

@@ -0,0 +1 @@
wger Workout Manager

View File

@@ -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...
- Plan workouts and nutrition
- Save exercises and comment them
- Gym mode
- Diary and tracking of development

View File

@@ -1 +1 @@
Fitness/workout, nutrition and weight tracker
Fitness/workout, nutrition and weight tracker

View File

@@ -1 +1 @@
wger Workout Manager
wger Workout Manager

View File

@@ -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

View File

@@ -0,0 +1 @@
Fitness / entraînement, nutrition et tracker de poids

View File

@@ -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

View File

@@ -0,0 +1 @@
Monitoraggio fitness/workout, dieta e peso

View File

@@ -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

View File

@@ -0,0 +1 @@
Fitness/treningsøkt, ernæring og vektlogging

View File

@@ -0,0 +1 @@
wger Workout Manager

View File

@@ -5,14 +5,12 @@
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.003772">
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.0022505">
</testcase>
<testcase classname="fastlane.lanes" name="1: assembleRelease" time="0.1341042">
<failure message="C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/actions/actions_helper.rb:67:in `execute_action'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:255:in `block in execute_action'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:229:in `chdir'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:229:in `execute_action'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:157:in `trigger_action_by_name'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/fast_file.rb:159:in `method_missing'&#10;Fastfile:20:in `block in parsing_binding'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/lane.rb:33:in `call'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:49:in `block in execute'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:45:in `chdir'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/runner.rb:45:in `execute'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/lane_manager.rb:47:in `cruise_lane'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/command_line_handler.rb:36:in `handle'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/commands_generator.rb:108:in `block (2 levels) in run'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/commander-fastlane-4.4.6/lib/commander/command.rb:178:in `call'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/commander-fastlane-4.4.6/lib/commander/command.rb:153:in `run'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/commander-fastlane-4.4.6/lib/commander/runner.rb:476:in `run_active_command'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb:76:in `run!'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/commander-fastlane-4.4.6/lib/commander/delegates.rb:15:in `run!'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/commands_generator.rb:352:in `run'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/commands_generator.rb:41:in `start'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/fastlane/lib/fastlane/cli_tools_distributor.rb:122:in `take_off'&#10;C:/Ruby27-x64/lib/ruby/gems/2.7.0/gems/fastlane-2.172.0/bin/fastlane:23:in `&lt;top (required)&gt;'&#10;C:/Ruby27-x64/bin/fastlane:23:in `load'&#10;C:/Ruby27-x64/bin/fastlane:23:in `&lt;main&gt;'&#10;&#10;Exit status of command '&quot;C:/Users/Roland Geider/GitHub/wger_repos/flutter/android/gradlew&quot; assembleRelease -p .' was 1 instead of 0.&#10;&#10;ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.&#10;&#10;Please set the JAVA_HOME variable in your environment to match the&#10;location of your Java installation.&#10;" />
<testcase classname="fastlane.lanes" name="1: upload_to_play_store" time="44.4966676">
</testcase>

View File

@@ -16,30 +16,19 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
/// 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;
Future<Widget> showFormBottomSheet(BuildContext context, String header, Widget form) async {
return showModalBottomSheet(
isScrollControlled: true,
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,
)
],
);
});
}
/// Default wger server during login
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;
/// Time to locally cache values such as ingredients, etc
const DAYS_TO_CACHE = 20;

View File

@@ -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;
}

View File

@@ -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();
},
@@ -50,15 +50,15 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, BuildContext cont
log('-------------------');
List<Widget> 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();
},

View File

@@ -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"
},
@@ -163,5 +163,115 @@
"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"
},
"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"
}
}

View File

@@ -1,5 +1,65 @@
{
"@@last_modified": "2020-11-11T15:04:05.523531",
"login": "Log in",
"@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",
"@password": {},
"confirmPassword": "Confirm password",
"@confirmPassword": {},
"invalidEmail": "Please enter a valid e-mail address",
"@invalidEmail": {
"description": "Error message when the user enters an invalid 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"
},
"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",
"@registerInstead": {},
"loginInstead": "Log in instead",
"@loginInstead": {},
"labelWorkoutPlans": "Workout plans",
"@labelWorkoutPlans": {
"description": "Title for screen workout plans"
@@ -24,14 +84,38 @@
"@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"
},
"reps": "Reps",
"@reps": {
"description": "Shorthand for repetitions, used when space constraints are tighter"
},
"rir": "RiR",
"@rir": {
"description": "Shorthand for Repetitions In Reserve"
},
"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"
@@ -54,10 +138,16 @@
"@newSet": {
"description": "Header when adding a new set to a workout day"
},
"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"
},
"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.",
"@logHelpEntriesUnits": {},
"description": "Description",
"@description": {},
"save": "Save",
@@ -78,6 +168,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",
@@ -138,10 +232,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...",
@@ -150,14 +252,61 @@
},
"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",
"@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"
},
"calendar": "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"
},
"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",
"type": "text",
"placeholders": {
"min": {},
"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,.,.,.')"
},
"selectIngredient": "Please select an ingredient",
"@selectIngredient": {
"description": "Error message when the user hasn't selected an ingredient from the autocompleter"
}
}

270
lib/l10n/app_fr.arb Normal file
View File

@@ -0,0 +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"
}
}

270
lib/l10n/app_it.arb Normal file
View File

@@ -0,0 +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"
}
}

View File

@@ -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"
},
@@ -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"
}
}

View File

@@ -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';
@@ -50,34 +51,27 @@ class MyApp extends StatelessWidget {
ChangeNotifierProvider(
create: (ctx) => Auth(),
),
ChangeNotifierProxyProvider<Auth, WorkoutPlans>(
create: null, // TODO: Create is required but it can be null??
update: (context, auth, previous) => WorkoutPlans(
auth,
previous == null ? [] : previous.items,
),
),
ChangeNotifierProxyProvider<Auth, Exercises>(
create: null, // TODO: Create is required but it can be null??
update: (context, auth, previous) => Exercises(
auth,
previous == null ? [] : previous.items,
create: (context) => Exercises(Provider.of<Auth>(context, listen: false), []),
update: (context, auth, previous) => previous != null ? previous : Exercises(auth, []),
),
ChangeNotifierProxyProvider2<Auth, Exercises, WorkoutPlans>(
create: (context) => WorkoutPlans(
Provider.of<Auth>(context, listen: false),
Provider.of<Exercises>(context, listen: false),
[],
),
update: (context, auth, exercises, previous) =>
previous != null ? previous : WorkoutPlans(auth, exercises, []),
),
ChangeNotifierProxyProvider<Auth, Nutrition>(
create: null, // TODO: Create is required but it can be null??
update: (context, auth, previous) => Nutrition(
auth,
previous == null ? [] : previous.items,
),
create: (context) => Nutrition(Provider.of<Auth>(context, listen: false), []),
update: (context, auth, previous) => previous != null ? previous : Nutrition(auth, []),
),
ChangeNotifierProxyProvider<Auth, BodyWeight>(
create: null, // TODO: Create is required but it can be null??
update: (context, auth, previous) => BodyWeight(
auth,
previous == null ? [] : previous.items,
),
)
create: (context) => BodyWeight(Provider.of<Auth>(context, listen: false), []),
update: (context, auth, previous) => previous != null ? previous : BodyWeight(auth, []),
),
],
child: Consumer<Auth>(
builder: (ctx, auth, _) => MaterialApp(
@@ -101,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,

View File

@@ -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<String, dynamic> json) => _$WeightEntryFromJson(json);

View File

@@ -9,8 +9,8 @@ part of 'weight_entry.dart';
WeightEntry _$WeightEntryFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const ['id', 'weight', 'date']);
return WeightEntry(
id: json['id'] as int,
weight: toNum(json['weight'] as String),
id: json['id'] as int?,
weight: toNum(json['weight'] as String?),
date: json['date'] == null ? null : DateTime.parse(json['date'] as String),
);
}

View File

@@ -29,8 +29,8 @@ class ExerciseCategory {
final String name;
ExerciseCategory({
this.id,
this.name,
required this.id,
required this.name,
});
@override

View File

@@ -29,8 +29,8 @@ class Comment {
final String comment;
Comment({
this.id,
this.comment,
required this.id,
required this.comment,
});
// Boilerplate

View File

@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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

View File

@@ -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<Muscle> muscles = [];
@@ -61,21 +64,31 @@ class Exercise {
List<Comment> 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<Muscle>? muscles,
List<Muscle>? musclesSecondary,
List<Equipment>? equipment,
List<ExerciseImage>? images,
List<Comment>? 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);
ExerciseImage? get getMainImage {
try {
return images.firstWhere((image) => image.isMain);
} on StateError catch (e) {
return null;
}
}
// Boilerplate

View File

@@ -23,49 +23,41 @@ Exercise _$ExerciseFromJson(Map<String, dynamic> 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<String, dynamic>),
muscles: (json['muscles'] as List)
?.map((e) =>
e == null ? null : Muscle.fromJson(e as Map<String, dynamic>))
?.toList(),
musclesSecondary: (json['muscles_secondary'] as List)
?.map((e) =>
e == null ? null : Muscle.fromJson(e as Map<String, dynamic>))
?.toList(),
equipment: (json['equipment'] as List)
?.map((e) =>
e == null ? null : Equipment.fromJson(e as Map<String, dynamic>))
?.toList(),
images: (json['images'] as List)
?.map((e) => e == null
? null
: ExerciseImage.fromJson(e as Map<String, dynamic>))
?.toList(),
tips: (json['comments'] as List)
?.map((e) =>
e == null ? null : Comment.fromJson(e as Map<String, dynamic>))
?.toList(),
);
categoryId: json['categoryId'] as int,
muscles: (json['muscles'] as List<dynamic>?)
?.map((e) => Muscle.fromJson(e as Map<String, dynamic>))
.toList(),
musclesSecondary: (json['muscles_secondary'] as List<dynamic>?)
?.map((e) => Muscle.fromJson(e as Map<String, dynamic>))
.toList(),
equipment: (json['equipment'] as List<dynamic>?)
?.map((e) => Equipment.fromJson(e as Map<String, dynamic>))
.toList(),
images: (json['images'] as List<dynamic>?)
?.map((e) => ExerciseImage.fromJson(e as Map<String, dynamic>))
.toList(),
tips: (json['comments'] as List<dynamic>?)
?.map((e) => Comment.fromJson(e as Map<String, dynamic>))
.toList(),
)..categoryObj =
ExerciseCategory.fromJson(json['category'] as Map<String, dynamic>);
}
Map<String, dynamic> _$ExerciseToJson(Exercise instance) => <String, dynamic>{
'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(),
};

View File

@@ -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,8 +38,11 @@ class ExerciseImage {
final bool isMain;
ExerciseImage({
this.url,
this.isMain,
required this.id,
required this.uuid,
required this.exerciseId,
required this.url,
required this.isMain,
});
// Boilerplate

View File

@@ -7,15 +7,21 @@ part of 'image.dart';
// **************************************************************************
ExerciseImage _$ExerciseImageFromJson(Map<String, dynamic> 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,
isMain: json['is_main'] as bool? ?? false,
);
}
Map<String, dynamic> _$ExerciseImageToJson(ExerciseImage instance) =>
<String, dynamic>{
'id': instance.id,
'uuid': instance.uuid,
'exercise': instance.exerciseId,
'image': instance.url,
'is_main': instance.isMain,
};

View File

@@ -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

View File

@@ -19,7 +19,7 @@
import 'dart:convert';
class WgerHttpException implements Exception {
Map<String, dynamic> errors;
Map<String, dynamic>? 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(', ');
}
}

View File

@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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

View File

@@ -23,17 +23,15 @@ Ingredient _$IngredientFromJson(Map<String, dynamic> 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?),
);
}

View File

@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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

View File

@@ -16,14 +16,11 @@ IngredientWeightUnit _$IngredientWeightUnitFromJson(Map<String, dynamic> json) {
]);
return IngredientWeightUnit(
id: json['id'] as int,
weightUnit: json['weight_unit'] == null
? null
: WeightUnit.fromJson(json['weight_unit'] as Map<String, dynamic>),
ingredient: json['ingredient'] == null
? null
: Ingredient.fromJson(json['ingredient'] as Map<String, dynamic>),
weightUnit:
WeightUnit.fromJson(json['weight_unit'] as Map<String, dynamic>),
ingredient: Ingredient.fromJson(json['ingredient'] as Map<String, dynamic>),
grams: json['grams'] as int,
amount: (json['amount'] as num)?.toDouble(),
amount: (json['amount'] as num).toDouble(),
);
}

View File

@@ -29,45 +29,46 @@ part 'log.g.dart';
@JsonSerializable()
class Log {
@JsonKey(required: true)
int id;
int? id;
@JsonKey(required: true, name: 'plan')
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 weightUnitId;
IngredientWeightUnit weightUnitObj;
@JsonKey(ignore: true)
IngredientWeightUnit? weightUnitObj;
@JsonKey(required: true, fromJson: toNum)
num amount;
late num amount;
Log({
this.id,
this.ingredientId,
this.ingredientObj,
this.weightUnit,
this.weightUnitObj,
this.amount,
this.planId,
this.datetime,
required this.ingredientId,
required this.weightUnitId,
required this.amount,
required this.planId,
required this.datetime,
this.comment,
});
Log.fromMealItem(MealItem mealItem) {
Log.fromMealItem(MealItem mealItem, this.planId, [DateTime? dateTime]) {
this.ingredientId = mealItem.ingredientId;
this.ingredientObj = mealItem.ingredientObj;
this.weightUnit = null;
this.weightUnitId = mealItem.weightUnitId;
this.datetime = dateTime ?? DateTime.now();
this.amount = mealItem.amount;
}
@@ -80,25 +81,18 @@ 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;
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;
}

View File

@@ -16,33 +16,22 @@ Log _$LogFromJson(Map<String, dynamic> 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<String, dynamic>),
weightUnit: json['weight_unit'] as int,
weightUnitObj: json['weightUnitObj'] == null
? null
: IngredientWeightUnit.fromJson(
json['weightUnitObj'] as Map<String, dynamic>),
amount: toNum(json['amount'] as String),
weightUnitId: json['weight_unit'] as int,
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<String, dynamic> _$LogToJson(Log instance) => <String, dynamic>{
'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,
'weight_unit': instance.weightUnitId,
'amount': instance.amount,
};

View File

@@ -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;
@JsonKey(name: 'plan')
late int planId;
@JsonKey(required: true, toJson: timeToString, fromJson: stringToTime)
TimeOfDay time;
@JsonKey(toJson: timeToString, fromJson: stringToTime)
late TimeOfDay time;
@JsonKey(required: false, name: 'meal_items', defaultValue: [])
@JsonKey(ignore: true, name: 'meal_items', defaultValue: [])
List<MealItem> mealItems = [];
Meal({
this.id,
this.plan,
this.time,
this.mealItems,
});
int? plan,
TimeOfDay? time,
List<MealItem>? mealItems,
}) {
if (plan != null) {
this.planId = plan;
}
this.mealItems = mealItems ?? [];
this.time = time ?? TimeOfDay.now();
}
// Boilerplate
factory Meal.fromJson(Map<String, dynamic> json) => _$MealFromJson(json);

View File

@@ -7,22 +7,14 @@ part of 'meal.dart';
// **************************************************************************
Meal _$MealFromJson(Map<String, dynamic> 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<String, dynamic>))
?.toList() ??
[],
);
id: json['id'] as int?,
time: stringToTime(json['time'] as String?),
)..planId = json['plan'] as int;
}
Map<String, dynamic> _$MealToJson(Meal instance) => <String, dynamic>{
'id': instance.id,
'plan': instance.plan,
'plan': instance.planId,
'time': timeToString(instance.time),
'meal_items': instance.mealItems,
};

View File

@@ -28,29 +28,37 @@ part 'meal_item.g.dart';
@JsonSerializable()
class MealItem {
@JsonKey(required: true)
final int id;
int? id;
@JsonKey(required: false)
late int mealId;
@JsonKey(required: false, name: 'ingredient')
int ingredientId;
@JsonKey(required: false, name: 'ingredient_obj')
Ingredient ingredientObj;
@JsonKey(required: false)
int meal;
@JsonKey(ignore: true)
late Ingredient ingredientObj;
@JsonKey(required: false, name: 'weight_unit')
IngredientWeightUnit weightUnit;
int weightUnitId;
@JsonKey(ignore: true)
late IngredientWeightUnit weightUnitObj;
@JsonKey(required: true, fromJson: toNum, toJson: toString)
num amount;
MealItem({
this.id,
this.ingredientObj,
this.weightUnit,
this.amount,
});
int? mealId,
required this.ingredientId,
required this.weightUnitId,
required this.amount,
}) {
if (mealId != null) {
this.mealId = mealId;
}
}
// Boilerplate
factory MealItem.fromJson(Map<String, dynamic> json) => _$MealItemFromJson(json);
@@ -62,24 +70,17 @@ 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.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;
}

View File

@@ -9,25 +9,18 @@ part of 'meal_item.dart';
MealItem _$MealItemFromJson(Map<String, dynamic> 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<String, dynamic>),
weightUnit: json['weight_unit'] == null
? null
: IngredientWeightUnit.fromJson(
json['weight_unit'] as Map<String, dynamic>),
amount: toNum(json['amount'] as String),
)
..ingredientId = json['ingredient'] as int
..meal = json['meal'] as int;
id: json['id'] as int?,
mealId: json['mealId'] as int?,
ingredientId: json['ingredient'] as int,
weightUnitId: json['weight_unit'] as int,
amount: toNum(json['amount'] as String?),
);
}
Map<String, dynamic> _$MealItemToJson(MealItem instance) => <String, dynamic>{
'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),
};

View File

@@ -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;
@@ -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<Meal> meals = [];
@JsonKey(ignore: true, defaultValue: [])
@@ -44,11 +44,14 @@ class NutritionalPlan {
NutritionalPlan({
this.id,
this.description,
this.creationDate,
this.meals,
//this.logs,
});
required this.description,
required this.creationDate,
List<Meal>? meals,
List<Log>? logs,
}) {
this.meals = meals ?? [];
this.logs = logs ?? [];
}
// Boilerplate
factory NutritionalPlan.fromJson(Map<String, dynamic> json) => _$NutritionalPlanFromJson(json);
@@ -59,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;
@@ -72,11 +73,12 @@ class NutritionalPlan {
var out = <DateTime, NutritionalValues>{};
for (var log in logs) {
final date = DateTime(log.datetime.year, log.datetime.month, log.datetime.day);
if (!out.containsKey(date)) {
out[date] = NutritionalValues();
}
out[date].add(log.nutritionalValues);
out[date]!.add(log.nutritionalValues);
}
return out;

View File

@@ -9,16 +9,9 @@ part of 'nutritional_plan.dart';
NutritionalPlan _$NutritionalPlanFromJson(Map<String, dynamic> 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<String, dynamic>))
?.toList() ??
[],
creationDate: DateTime.parse(json['creation_date'] as String),
);
}
@@ -27,5 +20,4 @@ Map<String, dynamic> _$NutritionalPlanToJson(NutritionalPlan instance) =>
'id': instance.id,
'description': instance.description,
'creation_date': toDate(instance.creationDate),
'meals': instance.meals?.map((e) => e?.toJson())?.toList(),
};

View File

@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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

View File

@@ -1,37 +1,42 @@
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';
@JsonSerializable()
class Day {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
String description;
@JsonKey(required: false, name: 'day', defaultValue: [])
List<int> daysOfWeek = [];
//@JsonKey(required: false)
List<Set> sets = [];
int? id;
@JsonKey(required: true, name: 'training')
int workoutId;
late int workoutId;
//@JsonKey(required: true, name: 'training')
WorkoutPlan workout;
@JsonKey(required: true)
late String description;
Day({
this.id,
this.workoutId,
this.description,
this.daysOfWeek,
this.sets,
@JsonKey(required: true, name: 'day')
List<int> daysOfWeek = [];
@JsonKey(ignore: true)
List<Set> sets = [];
//@JsonKey(ignore: true)
//late WorkoutPlan workout;
Day() {
this.daysOfWeek = [];
this.sets = [];
}
Day.withData({
required this.id,
required this.workoutId,
required this.description,
List<int>? daysOfWeek,
List<Set>? sets,
}) {
this.daysOfWeek = daysOfWeek ?? [];
this.sets = sets ?? [];
}
static const Map<int, String> weekdays = {
@@ -45,7 +50,7 @@ class Day {
};
String getDayName(int weekDay) {
return weekdays[weekDay];
return weekdays[weekDay]!;
}
String get getDaysText {

View File

@@ -7,26 +7,18 @@ part of 'day.dart';
// **************************************************************************
Day _$DayFromJson(Map<String, dynamic> 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<String, dynamic>))
?.toList(),
)
$checkKeys(json,
requiredKeys: const ['id', 'training', 'description', 'day']);
return Day()
..id = json['id'] as int?
..workoutId = json['training'] as int
..workout = json['workout'] == null
? null
: WorkoutPlan.fromJson(json['workout'] as Map<String, dynamic>);
..description = json['description'] as String
..daysOfWeek = (json['day'] as List<dynamic>).map((e) => e as int).toList();
}
Map<String, dynamic> _$DayToJson(Day instance) => <String, dynamic>{
'id': instance.id,
'training': instance.workoutId,
'description': instance.description,
'day': instance.daysOfWeek,
'sets': instance.sets,
'training': instance.workoutId,
'workout': instance.workout,
};

View File

@@ -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

View File

@@ -17,17 +17,16 @@ Log _$LogFromJson(Map<String, dynamic> 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<String, dynamic> _$LogToJson(Log instance) => <String, dynamic>{

View File

@@ -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

View File

@@ -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

View File

@@ -15,15 +15,14 @@ WorkoutSession _$WorkoutSessionFromJson(Map<String, dynamic> 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<String, dynamic> _$WorkoutSessionToJson(WorkoutSession instance) =>

View File

@@ -9,44 +9,55 @@ 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;
int? order;
//@JsonKey(required: true)
@JsonKey(ignore: true)
List<Exercise> exercisesObj = [];
@JsonKey(required: false, name: 'exercises')
@JsonKey(ignore: true)
List<int> exercisesIds = [];
@JsonKey(required: false)
@JsonKey(ignore: true)
List<Setting> 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<Setting> settingsComputed = [];
Set({
required this.day,
required this.sets,
this.order,
});
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) {

View File

@@ -9,19 +9,10 @@ part of 'set.dart';
Set _$SetFromJson(Map<String, dynamic> 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<String, dynamic>))
?.toList()
..exercisesIds =
(json['exercises'] as List)?.map((e) => e as int)?.toList();
sets: json['sets'] as int,
order: json['order'] as int?,
)..id = json['id'] as int?;
}
Map<String, dynamic> _$SetToJson(Set instance) => <String, dynamic>{
@@ -29,8 +20,4 @@ Map<String, dynamic> _$SetToJson(Set instance) => <String, dynamic>{
'sets': instance.sets,
'exerciseday': instance.day,
'order': instance.order,
'exercisesObj': instance.exercisesObj,
'exercises': instance.exercisesIds,
'settings': instance.settings,
'settingsComputed': instance.settingsComputed,
};

View File

@@ -1,63 +1,96 @@
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';
@JsonSerializable()
class Setting {
static final possibleValues = ['1', '1.5', '2', '2.5', '3', '3.5'];
@JsonKey(required: true)
int id;
int? id;
@JsonKey(required: true, name: 'set')
int setId;
@JsonKey(required: false)
Exercise exerciseObj;
@JsonKey(required: true, name: 'exercise')
int exerciseId;
@JsonKey(required: true, name: 'repetition_unit')
int repetitionUnit;
late int setId;
@JsonKey(required: true)
int reps;
late int order;
@JsonKey(ignore: true)
late Exercise exerciseObj;
@JsonKey(required: true, name: 'exercise')
late int exerciseId;
@JsonKey(required: true, name: 'repetition_unit')
late int repetitionUnitId;
@JsonKey(ignore: true)
late RepetitionUnit repetitionUnitObj;
@JsonKey(required: true)
int? reps;
@JsonKey(required: true, fromJson: toNum, toJson: toString)
num weight;
num? weight;
@JsonKey(required: true, name: 'weight_unit')
int weightUnit;
late int weightUnitId;
@JsonKey(required: true, defaultValue: '')
String comment = '';
@JsonKey(ignore: true)
late WeightUnit weightUnitObj;
@JsonKey(required: false, defaultValue: '')
String rir = '';
@JsonKey(required: true)
late String comment = '';
@JsonKey(required: true)
String? rir = '';
// Generated by Server
@JsonKey(required: false)
String repsText;
@JsonKey(ignore: true)
late String repsText = '';
Setting({
this.id,
this.setId,
this.exerciseObj,
this.repetitionUnit,
this.reps,
this.weight,
this.weightUnit,
this.comment,
this.rir,
this.repsText,
}) {
if (exerciseObj != null) {
this.exerciseId = exerciseObj.id;
}
}
required this.setId,
required this.order,
required this.exerciseId,
required this.repetitionUnitId,
required this.reps,
required this.weightUnitId,
required this.comment,
required this.rir,
});
Setting.empty();
// Boilerplate
factory Setting.fromJson(Map<String, dynamic> json) => _$SettingFromJson(json);
Map<String, dynamic> 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');
}
}
}

View File

@@ -10,39 +10,37 @@ Setting _$SettingFromJson(Map<String, dynamic> json) {
$checkKeys(json, requiredKeys: const [
'id',
'set',
'order',
'exercise',
'repetition_unit',
'reps',
'weight',
'weight_unit',
'comment'
'comment',
'rir'
]);
return Setting(
id: json['id'] as int,
id: json['id'] as int?,
setId: json['set'] as int,
exerciseObj: json['exerciseObj'] == null
? null
: Exercise.fromJson(json['exerciseObj'] as Map<String, dynamic>),
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;
order: json['order'] 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?,
)..weight = toNum(json['weight'] as String?);
}
Map<String, dynamic> _$SettingToJson(Setting instance) => <String, dynamic>{
'id': instance.id,
'set': instance.setId,
'exerciseObj': instance.exerciseObj,
'order': instance.order,
'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,
};

View File

@@ -11,8 +11,8 @@ class WeightUnit {
final String name;
WeightUnit({
this.id,
this.name,
required this.id,
required this.name,
});
// Boilerplate

View File

@@ -26,7 +26,7 @@ part 'workout_plan.g.dart';
@JsonSerializable()
class WorkoutPlan {
@JsonKey(required: true)
final int id;
int? id;
@JsonKey(required: true, name: 'creation_date')
DateTime creationDate;
@@ -34,18 +34,22 @@ class WorkoutPlan {
@JsonKey(required: true, name: 'comment')
String description;
@JsonKey(required: false, defaultValue: [], name: 'days')
@JsonKey(ignore: true)
List<Day> days = [];
@JsonKey(ignore: true, defaultValue: [])
@JsonKey(ignore: true)
List<Log> logs = [];
WorkoutPlan({
this.id,
this.creationDate,
this.description,
this.days,
});
required this.creationDate,
required this.description,
List<Day>? days,
List<Log>? logs,
}) {
this.days = days ?? [];
this.logs = logs ?? [];
}
// Boilerplate
factory WorkoutPlan.fromJson(Map<String, dynamic> json) => _$WorkoutPlanFromJson(json);

View File

@@ -9,23 +9,15 @@ part of 'workout_plan.dart';
WorkoutPlan _$WorkoutPlanFromJson(Map<String, dynamic> 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),
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) =>
e == null ? null : Day.fromJson(e as Map<String, dynamic>))
?.toList() ??
[],
);
}
Map<String, dynamic> _$WorkoutPlanToJson(WorkoutPlan instance) =>
<String, dynamic>{
'id': instance.id,
'creation_date': instance.creationDate?.toIso8601String(),
'creation_date': instance.creationDate.toIso8601String(),
'comment': instance.description,
'days': instance.days,
};

View File

@@ -28,15 +28,16 @@ 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';
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;
@@ -49,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) {
@@ -64,7 +65,7 @@ class Auth with ChangeNotifier {
/// Server application version
Future<void> 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;
}
@@ -76,8 +77,13 @@ class Auth with ChangeNotifier {
}
/// Registers a new user
Future<void> register({String username, String password, String email, String serverUrl}) async {
final uri = Uri.http(serverUrl, '/api/v2/register/');
Future<void> register({
required String username,
required String password,
required String email,
required String serverUrl,
}) async {
final uri = Uri.parse(serverUrl + '/api/v2/register/');
Map<String, String> metadata = Map();
// Read the api key from the manifest file
@@ -115,7 +121,7 @@ class Auth with ChangeNotifier {
/// Authenticates a user
Future<void> 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 {
@@ -133,7 +139,7 @@ class Auth with ChangeNotifier {
}
// Log user in
this.serverUrl = serverUrl ?? '';
this.serverUrl = serverUrl;
token = responseData['token'];
// _userId = responseData['localId'];
@@ -152,31 +158,45 @@ 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<String> getServerUrlFromPrefs() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('lastServer')) {
return DEFAULT_SERVER;
}
final userData = json.decode(prefs.getString('lastServer')!);
return userData['serverUrl'] as String;
}
Future<bool> tryAutoLogin() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
log('autologin failed');
return false;
}
final extractedUserData = json.decode(prefs.getString('userData')) as Map<String, Object>;
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;
@@ -192,6 +212,7 @@ class Auth with ChangeNotifier {
log('logging out');
token = null;
serverUrl = null;
dataInit = false;
// _userId = null;
// _expiryDate = null;
// if (_authTimer != null) {

View File

@@ -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<String, dynamic> query}) {
return makeUri(auth.serverUrl, path, id, objectMethod, query);
makeUrl(String path, {int? id, String? objectMethod, Map<String, dynamic>? query}) {
return makeUri(auth.serverUrl!, path, id, objectMethod, query);
}
/// Fetch and retrieve the overview list of objects, returns the JSON parsed response
Future<Map<String, dynamic>> fetch([Uri uri]) async {
Future<Map<String, dynamic>> fetch(Uri uri) async {
// Send the request
final response = await client.get(
uri,

View File

@@ -27,7 +27,7 @@ class BodyWeight extends WgerBaseProvider with ChangeNotifier {
static const bodyWeightUrl = 'weightentry';
List<WeightEntry> _entries = [];
BodyWeight(Auth auth, List<WeightEntry> entries, [http.Client client])
BodyWeight(Auth auth, List<WeightEntry> 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;
}
}

View File

@@ -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';
@@ -48,7 +49,7 @@ class Exercises extends WgerBaseProvider with ChangeNotifier {
List<Muscle> _muscles = [];
List<Equipment> _equipment = [];
Exercises(Auth auth, List<Exercise> entries, [http.Client client])
Exercises(Auth auth, List<Exercise> entries, [http.Client? client])
: this._exercises = entries,
super(auth, client);
@@ -57,10 +58,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<void> fetchAndSetCategories() async {
@@ -103,7 +101,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)));
@@ -123,11 +121,11 @@ class Exercises extends WgerBaseProvider with ChangeNotifier {
_exercisesUrlPath,
query: {'limit': '1000'},
));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final exercisesData = json.decode(response.body) as Map<String, dynamic>;
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 = {
@@ -141,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);
}
}

View File

@@ -17,7 +17,13 @@
*/
/// Helper function to make a URL.
makeUri(String serverUrl, String path, [int id, String objectMethod, Map<String, dynamic> query]) {
makeUri(
String serverUrl,
String path, [
int? id,
String? objectMethod,
Map<String, dynamic>? query,
]) {
Uri uriServer = Uri.parse(serverUrl);
var pathList = ['api', 'v2', path];

View File

@@ -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';
@@ -46,7 +44,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
List<NutritionalPlan> _plans = [];
List<Ingredient> _ingredients = [];
Nutrition(Auth auth, List<NutritionalPlan> entries, [http.Client client])
Nutrition(Auth auth, List<NutritionalPlan> entries, [http.Client? client])
: this._plans = entries,
super(auth, client);
@@ -56,7 +54,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,42 +64,65 @@ 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: () {});
if (meal != null) {
return meal;
}
var meal = plan.meals.firstWhere((plan) => plan.id == id);
return meal;
}
return null;
}
Future<List<NutritionalPlan>> fetchAndSetPlans() async {
final data =
await fetch(makeUrl(_nutritionalPlansInfoPath, query: {'ordering': '-creation_date'}));
final List<NutritionalPlan> loadedPlans = [];
/// Fetches and sets all nutritional plans
Future<void> fetchAndSetAllPlans() async {
final data = await fetch(makeUrl(_nutritionalPlansPath));
for (final entry in data['results']) {
loadedPlans.add(NutritionalPlan.fromJson(entry));
await fetchAndSetPlan(entry['id']);
}
_plans = loadedPlans;
notifyListeners();
return loadedPlans;
}
/// Fetches and sets the given nutritional plan
Future<NutritionalPlan> 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<Meal> meals = [];
final mealsData = await fetch(makeUrl(_mealPath, query: {'plan': planId.toString()}));
for (final mealEntry in mealsData['results']) {
List<MealItem> 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<NutritionalPlan> 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;
}
@@ -124,7 +145,7 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
notifyListeners();
throw WgerHttpException(response.body);
}
existingPlan = null;
//existingPlan = null;
}
/// Adds a meal to a plan
@@ -151,25 +172,24 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
/// Deletes a meal
Future<void> 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);
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<MealItem> 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);
@@ -183,43 +203,45 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
/// Deletes a meal
Future<void> 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);
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<Ingredient> fetchIngredient(int ingredientId) async {
var ingredient = _ingredients.firstWhere((e) => e.id == ingredientId, orElse: () => null);
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
@@ -227,7 +249,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 +269,10 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
/// Searches for an ingredient
Future<List> searchIngredient(String name) async {
if (name.length <= 1) {
return [];
}
// Send the request
final response = await client.get(
makeUrl(_ingredientSearchPath, query: {'term': name}),
@@ -269,10 +295,10 @@ class Nutrition extends WgerBaseProvider with ChangeNotifier {
Future<void> 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();
final plan = findById(meal.planId);
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'];

View File

@@ -22,8 +22,8 @@ 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';
import 'package:wger/models/workouts/day.dart';
import 'package:wger/models/workouts/log.dart';
@@ -35,10 +35,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';
@@ -48,13 +47,15 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
static const _weightUnitUrlPath = 'setting-weightunit';
static const _repetitionUnitUrlPath = 'setting-repetitionunit';
WorkoutPlan _currentPlan;
WorkoutPlan? _currentPlan;
Exercises _exercises;
List<WorkoutPlan> _workoutPlans = [];
List<WeightUnit> _weightUnits = [];
List<RepetitionUnit> _repetitionUnit = [];
WorkoutPlans(Auth auth, List<WorkoutPlan> entries, [http.Client client])
: this._workoutPlans = entries,
WorkoutPlans(Auth auth, Exercises exercises, List<WorkoutPlan> entries, [http.Client? client])
: this._exercises = exercises,
this._workoutPlans = entries,
super(auth, client);
List<WorkoutPlan> get items {
@@ -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<RepetitionUnit> 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;
}
@@ -113,6 +114,74 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
/*
* Workouts
*/
Future<void> fetchAndSetAllPlans() async {
final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'}));
for (final entry in data['results']) {
await fetchAndSetWorkoutPlan(entry['id']);
}
notifyListeners();
}
Future<void> fetchAndSetWorkoutPlan(int workoutId) async {
// Plan
final planData = await fetch(makeUrl(_workoutPlansUrlPath, id: workoutId));
final plan = WorkoutPlan.fromJson(planData);
// Days
List<Day> days = [];
final daysData = await fetch(makeUrl(_daysUrlPath, query: {'training': workoutId.toString()}));
for (final dayEntry in daysData['results']) {
final day = Day.fromJson(dayEntry);
// Sets
List<Set> 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<Setting> 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<void> fetchAndSetWorkouts() async {
final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'}));
final List<WorkoutPlan> loadedWorkoutPlans = [];
@@ -125,112 +194,6 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
notifyListeners();
}
Future<void> setAllFullWorkouts() async {
for (var plan in _workoutPlans) {
setFullWorkout(plan.id);
}
}
Future<WorkoutPlan> 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<Day> days = [];
for (final entry in data['day_list']) {
List<Set> sets = [];
for (final set in entry['set_list']) {
List<Setting> settings = [];
List<Setting> settingsComputed = [];
List<Exercise> exercises = [];
for (final exerciseData in set['exercise_list']) {
List<ExerciseImage> 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,
);
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 exerciseData['settings_computed']) {
settingsComputed.add(Setting.fromJson(setting));
}
}
// Sets
sets.add(Set(
id: set['obj']['id'],
sets: set['obj']['sets'],
order: set['obj']['order'],
settings: settings,
settingsComputed: settingsComputed,
exercises: exercises,
));
}
// 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;
// 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<WorkoutPlan> postWorkout(WorkoutPlan workout) async {
final data = await post(workout.toJson(), makeUrl(_workoutPlansUrlPath));
final plan = WorkoutPlan.fromJson(data);
@@ -242,7 +205,7 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
Future<WorkoutPlan> 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 +223,9 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
notifyListeners();
throw WgerHttpException(response.body);
}
existingWorkout = null;
}
Future<dynamic> fetchLogData(WorkoutPlan workout, Exercise exercise) async {
Future<Map<String, dynamic>> fetchLogData(WorkoutPlan workout, Exercise exercise) async {
final data = await fetch(
makeUrl(
_workoutPlansUrlPath,
@@ -305,15 +267,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;
}
}
@@ -340,7 +302,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 = [];
@@ -349,6 +311,14 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
return day;
}
Future<void> deleteDay(Day day) async {
await deleteRequest(_daysUrlPath, day.id!);
for (var workout in _workoutPlans) {
workout.days.removeWhere((element) => element.id == day.id);
}
notifyListeners();
}
/*
* Sets
*/
@@ -359,6 +329,17 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
return set;
}
Future<void> 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 +350,6 @@ class WorkoutPlans extends WgerBaseProvider with ChangeNotifier {
return setting;
}
Future<void> 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
*/

View File

@@ -17,7 +17,9 @@
*/
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';
@@ -82,9 +84,7 @@ class AuthScreen extends StatelessWidget {
}
class AuthCard extends StatefulWidget {
const AuthCard({
Key key,
}) : super(key: key);
const AuthCard();
@override
_AuthCardState createState() => _AuthCardState();
@@ -93,6 +93,7 @@ class AuthCard extends StatefulWidget {
class _AuthCardState extends State<AuthCard> {
final GlobalKey<FormState> _formKey = GlobalKey();
AuthMode _authMode = AuthMode.Login;
bool _hideCustomServer = true;
Map<String, String> _authData = {
'username': '',
'email': '',
@@ -104,14 +105,23 @@ class _AuthCardState extends State<AuthCard> {
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();
context.read<Auth>().getServerUrlFromPrefs().then((value) {
_serverUrlController.text = value;
});
}
void _submit(BuildContext context) async {
if (!_formKey.currentState.validate()) {
if (!_formKey.currentState!.validate()) {
// Invalid!
return;
}
_formKey.currentState.save();
_formKey.currentState!.save();
setState(() {
_isLoading = true;
});
@@ -119,18 +129,18 @@ class _AuthCardState extends State<AuthCard> {
// Login existing user
if (_authMode == AuthMode.Login) {
await Provider.of<Auth>(context, listen: false).login(
_authData['username'],
_authData['password'],
_authData['serverUrl'],
_authData['username']!,
_authData['password']!,
_authData['serverUrl']!,
);
// Register new user
} else {
await Provider.of<Auth>(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']!,
);
}
@@ -178,25 +188,25 @@ class _AuthCardState extends State<AuthCard> {
children: <Widget>[
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!';
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: 'E-Mail'),
decoration: InputDecoration(labelText: AppLocalizations.of(context)!.email),
autofillHints: [AutofillHints.email],
controller: _emailController,
keyboardType: TextInputType.emailAddress,
@@ -204,63 +214,96 @@ class _AuthCardState extends State<AuthCard> {
// Email is not required
validator: (value) {
if (value.isNotEmpty && !value.contains('@')) {
return 'Invalid email!';
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: '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!';
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: '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: <Widget>[
IconButton(
icon: const Icon(Icons.undo),
onPressed: () {
_serverUrlController.text = DEFAULT_SERVER;
},
),
Text(AppLocalizations.of(context)!.reset)
],
),
],
),
),
SizedBox(
height: 20,
@@ -270,16 +313,33 @@ class _AuthCardState extends State<AuthCard> {
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;
});
},
),
],
),
),

View File

@@ -37,15 +37,25 @@ class DashboardScreen extends StatefulWidget {
}
class _DashboardScreenState extends State<DashboardScreen> {
Future<void>? _initialData;
Widget getAppBar() {
return AppBar(
title: Text(AppLocalizations.of(context).labelDashboard),
title: Text(AppLocalizations.of(context)!.labelDashboard),
actions: [],
);
}
@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<void> _loadEntries(BuildContext context) async {
Future<void> _loadEntries() async {
if (!Provider.of<Auth>(context, listen: false).dataInit) {
Provider.of<Auth>(context, listen: false).setServerVersion();
@@ -53,40 +63,42 @@ class _DashboardScreenState extends State<DashboardScreen> {
await Provider.of<Exercises>(context, listen: false).fetchAndSetExercises();
// Nutrition
Nutrition nutritionProvider = Provider.of<Nutrition>(context, listen: false);
await nutritionProvider.fetchIngredientsFromCache();
await nutritionProvider.fetchAndSetPlans();
await nutritionProvider.fetchAndSetAllLogs();
await Provider.of<Nutrition>(context, listen: false).fetchIngredientsFromCache();
await Provider.of<Nutrition>(context, listen: false).fetchAndSetAllPlans();
await Provider.of<Nutrition>(context, listen: false).fetchAndSetAllLogs();
// Workouts
WorkoutPlans workoutProvider = Provider.of<WorkoutPlans>(context, listen: false);
await workoutProvider.fetchAndSetUnits();
await workoutProvider.fetchAndSetWorkouts();
await workoutProvider.setAllFullWorkouts();
if (workoutProvider.activePlan != null) {
workoutProvider.setCurrentPlan(workoutProvider.activePlan.id);
await Provider.of<WorkoutPlans>(context, listen: false).fetchAndSetUnits();
await Provider.of<WorkoutPlans>(context, listen: false).fetchAndSetAllPlans();
//await Provider.of<WorkoutPlans>(context, listen: false).fetchAndSetWorkouts();
//await Provider.of<WorkoutPlans>(context, listen: false).setAllFullWorkouts();
if (Provider.of<WorkoutPlans>(context, listen: false).activePlan != null) {
Provider.of<WorkoutPlans>(context, listen: false).setCurrentPlan(
Provider.of<WorkoutPlans>(context, listen: false).activePlan!.id!,
);
}
// Weight
await Provider.of<BodyWeight>(context, listen: false).fetchAndSetEntries();
}
Provider.of<Auth>(context, listen: false).dataInit = true;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: getAppBar(),
appBar: getAppBar() as PreferredSizeWidget?,
drawer: AppDrawer(),
body: FutureBuilder(
future: _loadEntries(context),
future: _initialData,
builder: (ctx, authResultSnapshot) =>
authResultSnapshot.connectionState == ConnectionState.waiting
? Column(
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)),
@@ -101,7 +113,7 @@ class _DashboardScreenState extends State<DashboardScreen> {
DashboardWeightWidget(context: context),
Container(
height: 650, // TODO: refactor calendar so we can get rid of size
child: DashboardCalendarWidget(title: 'Calendar'),
child: DashboardCalendarWidget(),
),
],
),

View File

@@ -0,0 +1,63 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* 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 <http://www.gnu.org/licenses/>.
*/
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(
backgroundColor: Colors.white,
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,
),
],
),
);
}
}

View File

@@ -32,7 +32,7 @@ class GymModeScreen extends StatefulWidget {
class _GymModeScreenState extends State<GymModeScreen> {
@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<WorkoutPlans>(

View File

@@ -31,7 +31,7 @@ class HomeTabsScreen extends StatefulWidget {
}
class _HomeTabsScreenState extends State<HomeTabsScreen> with SingleTickerProviderStateMixin {
TabController controller;
TabController? controller;
@override
initState() {

View File

@@ -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';
@@ -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),
@@ -53,16 +53,19 @@ 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
} else if (value == NutritionalPlanOptions.delete) {
Provider.of<Nutrition>(context, listen: false)
.deletePlan(_nutritionalPlan.id);
.deletePlan(_nutritionalPlan.id!);
Navigator.of(context).pushNamed(NutritionalPlanScreen.routeName);
}
},
@@ -70,12 +73,12 @@ class NutritionalPlanScreen extends StatelessWidget {
return [
PopupMenuItem<NutritionalPlanOptions>(
value: NutritionalPlanOptions.edit,
child: Text(AppLocalizations.of(context).edit),
child: Text(AppLocalizations.of(context)!.edit),
),
const PopupMenuDivider(),
PopupMenuItem<NutritionalPlanOptions>(
value: NutritionalPlanOptions.delete,
child: Text(AppLocalizations.of(context).delete),
child: Text(AppLocalizations.of(context)!.delete),
),
];
},

View File

@@ -19,10 +19,9 @@
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/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';
@@ -36,24 +35,26 @@ class NutritionScreen extends StatefulWidget {
class _NutritionScreenState extends State<NutritionScreen> {
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(
Navigator.pushNamed(
context,
AppLocalizations.of(context).newNutritionalPlan,
PlanForm(NutritionalPlan()),
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.newNutritionalPlan,
PlanForm(),
),
);
//await showNutritionalPlanSheet(context, nutritionalPlan);
},
),
body: Consumer<Nutrition>(

View File

@@ -18,11 +18,8 @@
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/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';
@@ -34,41 +31,31 @@ class WeightScreen extends StatefulWidget {
}
class _WeightScreenState extends State<WeightScreen> {
WeightEntry weightEntry = WeightEntry();
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(
Navigator.pushNamed(
context,
AppLocalizations.of(context).newEntry,
WeightForm(),
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.newEntry,
WeightForm(),
),
);
},
),
body: Consumer<BodyWeight>(
builder: (context, weightProvider, child) => WeightEntriesList(weightProvider),
),
);
}
showWeightEntrySheet(BuildContext context) async {
showModalBottomSheet(
context: context,
builder: (BuildContext ctx) {
return Container(margin: EdgeInsets.all(20), child: WeightForm());
},
body: WeightEntriesList(),
);
}
}

View File

@@ -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';
@@ -64,14 +64,14 @@ class _WorkoutPlanScreenState extends State<WorkoutPlanScreen> {
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),
@@ -81,22 +81,32 @@ class _WorkoutPlanScreenState extends State<WorkoutPlanScreen> {
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<WorkoutOptions>(
icon: Icon(Icons.more_vert),
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
} else if (value == WorkoutOptions.delete) {
Provider.of<WorkoutPlans>(context, listen: false)
.deleteWorkout(workoutPlan.id);
.deleteWorkout(workoutPlan.id!);
Navigator.of(context).pushNamed(WorkoutPlansScreen.routeName);
// Toggle Mode
@@ -112,7 +122,7 @@ class _WorkoutPlanScreenState extends State<WorkoutPlanScreen> {
return [
PopupMenuItem<WorkoutOptions>(
value: WorkoutOptions.edit,
child: Text(AppLocalizations.of(context).edit),
child: Text(AppLocalizations.of(context)!.edit),
),
PopupMenuItem<WorkoutOptions>(
child: _mode == WorkoutScreenMode.log
@@ -123,19 +133,12 @@ class _WorkoutPlanScreenState extends State<WorkoutPlanScreen> {
const PopupMenuDivider(),
PopupMenuItem<WorkoutOptions>(
value: WorkoutOptions.delete,
child: Text(AppLocalizations.of(context).delete),
child: Text(AppLocalizations.of(context)!.delete),
),
];
},
),
],
flexibleSpace: FlexibleSpaceBar(
title: Text(workoutPlan.description),
background: Image(
image: AssetImage('assets/images/backgrounds/workout_plans.jpg'),
fit: BoxFit.cover,
),
),
),
getBody(workoutPlan),
],

View File

@@ -22,8 +22,9 @@ 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';
@@ -35,24 +36,21 @@ class WorkoutPlansScreen extends StatefulWidget {
}
class _WorkoutPlansScreenState extends State<WorkoutPlansScreen> {
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(
Navigator.pushNamed(
context,
AppLocalizations.of(context).newWorkout,
WorkoutForm(WorkoutPlan()),
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.newWorkout,
WorkoutForm(WorkoutPlan(creationDate: DateTime.now(), description: '')),
),
);
},
),

View File

@@ -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

View File

@@ -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);
@@ -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),
@@ -112,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(
@@ -131,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',

View File

@@ -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);
}

View File

@@ -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<DateTime, List> _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();
@override
_DashboardCalendarWidgetState createState() => _DashboardCalendarWidgetState();
@@ -72,10 +72,10 @@ class DashboardCalendarWidget extends StatefulWidget {
class _DashboardCalendarWidgetState extends State<DashboardCalendarWidget>
with TickerProviderStateMixin {
Map<DateTime, List> _events;
List _selectedEvents;
AnimationController _animationController;
CalendarController _calendarController;
late Map<DateTime, List> _events;
late List _selectedEvents;
late AnimationController _animationController;
late CalendarController _calendarController;
@override
void initState() {
@@ -115,7 +115,7 @@ class _DashboardCalendarWidgetState extends State<DashboardCalendarWidget>
}
// 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<DashboardCalendarWidget>
}
// Add events to lists
_events[date].add(Event(
_events[date]!.add(Event(
EventType.session,
'Impression: ${session.impressionAsString} $time',
'${AppLocalizations.of(context)!.impression}: ${session.impressionAsString} $time',
));
}
});
@@ -151,7 +151,7 @@ class _DashboardCalendarWidgetState extends State<DashboardCalendarWidget>
}
// Add events to lists
_events[date].add(Event(
_events[date]!.add(Event(
EventType.caloriesDiary,
'${entry.value.energy.toStringAsFixed(0)} kcal',
));
@@ -185,7 +185,11 @@ class _DashboardCalendarWidgetState extends State<DashboardCalendarWidget>
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<DashboardCalendarWidget>
const SizedBox(height: 8.0),
_buildButtons(),
const SizedBox(height: 8.0),
//_buildEventList(),
Expanded(child: _buildEventList()),
],
),
@@ -358,7 +361,7 @@ class _DashboardCalendarWidgetState extends State<DashboardCalendarWidget>
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: Text('Go to today'),
child: Text(AppLocalizations.of(context)!.goToToday),
onPressed: () async {
final today = DateTime.now();
_calendarController.setSelectedDay(
@@ -396,13 +399,13 @@ class _DashboardCalendarWidgetState extends State<DashboardCalendarWidget>
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();
})()),

View File

@@ -26,18 +26,20 @@ 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/widgets/core/bottom_sheet.dart';
import 'package:wger/theme/theme.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({
Key key,
@required this.context,
}) : super(key: key);
required this.context,
});
final BuildContext context;
@@ -46,26 +48,76 @@ class DashboardNutritionWidget extends StatefulWidget {
}
class _DashboardNutritionWidgetState extends State<DashboardNutritionWidget> {
Nutrition nutrition;
NutritionalPlan plan;
//Nutrition nutrition;
late NutritionalPlan plan;
var showDetail = false;
@override
Widget build(BuildContext context) {
plan = Provider.of<Nutrition>(context, listen: false).currentPlan;
NutritionalPlan? plan = Provider.of<Nutrition>(context, listen: false).currentPlan;
final bool hasContent = plan != null;
List<Widget> out = [];
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.toStringAsFixed(0)}${AppLocalizations.of(context)!.kcal}'),
Text(' / '),
Text(
'${meal.nutritionalValues.protein.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'),
Text(' / '),
Text(
'${meal.nutritionalValues.carbohydrates.toStringAsFixed(0)}${AppLocalizations.of(context)!.g}'),
Text(' / '),
Text(
'${meal.nutritionalValues.fat.toStringAsFixed(0)}${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,
children: [
Text(
AppLocalizations.of(context).nutritionalPlan,
AppLocalizations.of(context)!.nutritionalPlan,
style: Theme.of(context).textTheme.headline4,
),
plan != null
hasContent
? Column(
children: [
Text(
DateFormat.yMd().format(plan.creationDate),
DateFormat.yMd(Localizations.localeOf(context).languageCode)
.format(plan.creationDate),
style: Theme.of(context).textTheme.headline6,
),
TextButton(
@@ -74,10 +126,11 @@ class _DashboardNutritionWidgetState extends State<DashboardNutritionWidget> {
style: TextStyle(fontSize: 20),
),
onPressed: () {
return Navigator.of(context)
Navigator.of(context)
.pushNamed(NutritionalPlanScreen.routeName, arguments: plan);
},
),
...out,
Container(
padding: EdgeInsets.all(15),
height: 180,
@@ -85,24 +138,22 @@ class _DashboardNutritionWidgetState extends State<DashboardNutritionWidget> {
)
],
)
: Container(
alignment: Alignment.center,
height: 150,
child: Text('You have no nutritional plans'),
: NothingFound(
AppLocalizations.of(context)!.noNutritionalPlans,
AppLocalizations.of(context)!.newNutritionalPlan,
PlanForm(),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
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),
],
),
],
@@ -113,9 +164,8 @@ class _DashboardNutritionWidgetState extends State<DashboardNutritionWidget> {
class DashboardWeightWidget extends StatefulWidget {
const DashboardWeightWidget({
Key key,
@required this.context,
}) : super(key: key);
required this.context,
});
final BuildContext context;
@@ -124,7 +174,7 @@ class DashboardWeightWidget extends StatefulWidget {
}
class _DashboardWeightWidgetState extends State<DashboardWeightWidget> {
BodyWeight weightEntriesData;
late BodyWeight weightEntriesData;
@override
Widget build(BuildContext context) {
@@ -135,7 +185,7 @@ class _DashboardWeightWidgetState extends State<DashboardWeightWidget> {
mainAxisSize: MainAxisSize.min,
children: [
Text(
AppLocalizations.of(context).weight,
AppLocalizations.of(context)!.weight,
style: Theme.of(context).textTheme.headline4,
),
Column(
@@ -146,21 +196,24 @@ class _DashboardWeightWidgetState extends State<DashboardWeightWidget> {
height: 180,
child: WeightChartWidget(weightEntriesData.items),
)
: Container(
alignment: Alignment.center,
height: 150,
child: Text('You have no weight entries'),
: NothingFound(
AppLocalizations.of(context)!.noWeightEntries,
AppLocalizations.of(context)!.newEntry,
WeightForm(),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: Text(AppLocalizations.of(context).newEntry),
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(),
),
);
},
),
@@ -176,9 +229,8 @@ class _DashboardWeightWidgetState extends State<DashboardWeightWidget> {
class DashboardWorkoutWidget extends StatefulWidget {
DashboardWorkoutWidget({
Key key,
@required this.context,
}) : super(key: key);
required this.context,
});
final BuildContext context;
@@ -187,42 +239,39 @@ class DashboardWorkoutWidget extends StatefulWidget {
}
class _DashboardWorkoutWidgetState extends State<DashboardWorkoutWidget> {
WorkoutPlan _workoutPlan;
late WorkoutPlan _workoutPlan;
var showDetail = false;
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
_workoutPlan = Provider.of<WorkoutPlans>(context, listen: false).activePlan;
WorkoutPlan? _workoutPlan = Provider.of<WorkoutPlans>(context, listen: false).activePlan;
final bool hasContent = _workoutPlan != null;
List<Widget> 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, style: TextStyle(fontWeight: FontWeight.bold)),
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: 5),
],
);
}).toList(),
SizedBox(height: 7),
],
));
});
}
}
}
@@ -231,14 +280,15 @@ class _DashboardWorkoutWidgetState extends State<DashboardWorkoutWidget> {
mainAxisSize: MainAxisSize.min,
children: [
Text(
AppLocalizations.of(context).labelWorkoutPlan,
AppLocalizations.of(context)!.labelWorkoutPlan,
style: Theme.of(context).textTheme.headline4,
),
_workoutPlan != null
hasContent
? Column(
children: [
Text(
DateFormat.yMd().format(_workoutPlan.creationDate),
DateFormat.yMd(Localizations.localeOf(context).languageCode)
.format(_workoutPlan.creationDate),
style: Theme.of(context).textTheme.headline6,
),
TextButton(
@@ -247,31 +297,69 @@ class _DashboardWorkoutWidgetState extends State<DashboardWorkoutWidget> {
style: TextStyle(fontSize: 20),
),
onPressed: () {
return Navigator.of(context)
Navigator.of(context)
.pushNamed(WorkoutPlanScreen.routeName, arguments: _workoutPlan);
},
),
...out,
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
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(creationDate: DateTime.now(), description: '')),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
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 {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
_titleForm,
_form,
),
);
},
),
],
),
);

View File

@@ -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<dynamic> 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<List<dynamic>, DateTime>(
charts.Series<List<dynamic>, 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<dynamic, DateTime>
],
defaultRenderer: new charts.BarRendererConfig<DateTime>(),
);

View File

@@ -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<FormState>();
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,12 +110,12 @@ 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();
MealItemForm(this._meal, [mealItem]) {
this._mealItem = mealItem;
//this._mealItem = mealItem ?? MealItem(mealId: _meal.id);
}
final _form = GlobalKey<FormState>();
@@ -124,13 +133,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<Nutrition>(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 +148,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 'Please select an ingredient';
if (value!.isEmpty) {
return AppLocalizations.of(context)!.selectIngredient;
}
if (mealItem.ingredientId == null) {
return 'Please select an ingredient';
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 'Please enter a valid number';
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<Nutrition>(context, listen: false).addMealItem(mealItem, meal.id);
Provider.of<Nutrition>(context, listen: false).addMealItem(_mealItem, _meal.id!);
} on WgerHttpException catch (error) {
showHttpExceptionErrorDialog(error, context);
} catch (error) {
@@ -198,45 +205,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<FormState>();
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<Nutrition>(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<Nutrition>(context, listen: false).patchPlan(plan);
} else {
await Provider.of<Nutrition>(context, listen: false).postPlan(_plan);
await Provider.of<Nutrition>(context, listen: false).postPlan(plan);
}
// Saving was successful, reset the data

View File

@@ -19,10 +19,12 @@
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';
import 'package:wger/widgets/core/bottom_sheet.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/theme/theme.dart';
import 'package:wger/widgets/core/core.dart';
import 'package:wger/widgets/nutrition/forms.dart';
@@ -59,21 +61,25 @@ class _MealWidgetState extends State<MealWidget> {
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(
Navigator.pushNamed(
context,
AppLocalizations.of(context).addIngredient,
MealItemForm(widget._meal),
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.addIngredient,
MealItemForm(widget._meal),
true,
),
);
},
),
@@ -92,50 +98,60 @@ class MealItemWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
String unit = _item.weightUnit == null
? AppLocalizations.of(context).g
: _item.weightUnit.weightUnit.name;
String unit = _item.weightUnitId == null
? AppLocalizations.of(context)!.g
: _item.weightUnitObj.weightUnit.name;
final values = _item.nutritionalValues;
return InkWell(
onLongPress: () {
// Delete the meal item
Provider.of<Nutrition>(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: ICON_SIZE_SMALL,
onPressed: () {
// Delete the meal item
Provider.of<Nutrition>(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}'),
],
),
],
),
);
}
@@ -148,10 +164,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;
@@ -159,31 +173,39 @@ class DismissibleMealHeader extends StatelessWidget {
Widget build(BuildContext context) {
return InkWell(
onLongPress: () {
showFormBottomSheet(
Navigator.pushNamed(
context,
AppLocalizations.of(context).edit,
MealForm(_meal.plan, _meal),
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.edit,
MealForm(_meal.planId, _meal),
),
);
},
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),
@@ -198,11 +220,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',
@@ -225,7 +247,7 @@ class DismissibleMealHeader extends StatelessWidget {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context).successfullyDeleted,
AppLocalizations.of(context)!.successfullyDeleted,
textAlign: TextAlign.center,
),
),
@@ -237,7 +259,7 @@ class DismissibleMealHeader extends StatelessWidget {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context).mealLogged,
AppLocalizations.of(context)!.mealLogged,
textAlign: TextAlign.center,
),
),

View File

@@ -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';
@@ -38,17 +38,19 @@ 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(
child: Text(AppLocalizations.of(context).add),
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!),
),
);
},
),
@@ -68,14 +70,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),
],
),
),
@@ -98,14 +100,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),
],
),
],
@@ -131,17 +133,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})'),
],
),
),

View File

@@ -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,
@@ -71,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),
),
),
),
);

View File

@@ -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/screens/form_screen.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<BodyWeight>(context, listen: false);
return Column(
children: [
Container(
@@ -50,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(
@@ -66,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;
}
@@ -103,8 +105,11 @@ class WeightEntriesList extends StatelessWidget {
child: Card(
child: ListTile(
onTap: () {},
title: Text(DateFormat.yMd().format(currentEntry.date).toString()),
subtitle: Text('${currentEntry.weight} kg'),
title: Text('${currentEntry.weight} kg'),
subtitle: Text(
DateFormat.yMd(Localizations.localeOf(context).languageCode)
.format(currentEntry.date),
),
),
),
);

View File

@@ -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 'Please enter a weight';
if (value!.isEmpty) {
return AppLocalizations.of(context)!.enterValue;
}
try {
double.parse(value);
} catch (error) {
return 'Please enter a valid number';
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 {

View File

@@ -19,54 +19,54 @@
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';
import 'package:wger/providers/workout_plans.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/screens/gym_mode.dart';
import 'package:wger/widgets/core/bottom_sheet.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 {
Setting setting;
final bool expanded;
final toggle;
SettingWidget({this.setting});
SettingWidget({required this.setting, required this.expanded, required this.toggle});
@override
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),
subtitle: Text(setting.repsText),
trailing: IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(Icons.delete),
//iconSize: 16,
onPressed: () {
Provider.of<WorkoutPlans>(context, listen: false).deleteSetting(setting);
},
),
);
}
}
class WorkoutDayWidget extends StatelessWidget {
class WorkoutDayWidget extends StatefulWidget {
final Day _day;
WorkoutDayWidget(this._day);
@override
_WorkoutDayWidgetState createState() => _WorkoutDayWidgetState();
}
class _WorkoutDayWidgetState extends State<WorkoutDayWidget> {
bool _expanded = false;
void _toggleExpanded() {
setState(() {
_expanded = !_expanded;
});
}
Widget getSetRow(Set set) {
return Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
@@ -77,76 +77,152 @@ class WorkoutDayWidget extends StatelessWidget {
children: [
...set.settings
.map(
(setting) => SettingWidget(setting: setting),
(setting) => SettingWidget(
setting: setting,
expanded: _expanded,
toggle: _toggleExpanded,
),
)
.toList(),
Divider(),
],
),
)
),
if (_expanded)
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(Icons.delete),
iconSize: ICON_SIZE_SMALL,
onPressed: () {
Provider.of<WorkoutPlans>(context, listen: false).deleteSet(set);
},
)
],
);
}
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: [
DayHeaderDismissible(day: _day),
..._day.sets
.map(
(set) => getSetRow(set),
)
.toList(),
OutlinedButton(
child: Text('Add exercise to day'),
onPressed: () {
showFormBottomSheet(
context,
AppLocalizations.of(context).newSet,
SetFormWidget(_day),
);
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
)
],
return Container(
padding: EdgeInsets.all(3),
child: Card(
child: Column(
children: [
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),
)
.toList(),
OutlinedButton(
child: Text(AppLocalizations.of(context)!.addExercise),
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context)!.newSet,
SetFormWidget(widget._day),
true,
),
);
},
),
],
),
),
);
}
}
class DayHeaderDismissible extends StatelessWidget {
const DayHeaderDismissible({
Key key,
@required Day day,
}) : _day = day,
super(key: key);
final Day _day;
final bool _expanded;
final _toggle;
const DayHeaderDismissible({
required Day day,
required bool expanded,
required Function toggle,
}) : _day = day,
_expanded = expanded,
_toggle = toggle;
@override
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),
width: double.infinity,
child: Column(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(color: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
_day.description,
style: Theme.of(context).textTheme.headline6,
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_day.description,
style: Theme.of(context).textTheme.headline5,
overflow: TextOverflow.ellipsis,
),
Text(_day.getDaysText),
],
),
),
Row(
children: [
if (_expanded)
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
Provider.of<WorkoutPlans>(context, listen: false).deleteDay(_day);
},
),
IconButton(
icon: _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more),
onPressed: () {
_toggle();
},
),
],
),
Text(_day.getDaysText),
],
),
),
/*
secondaryBackground: Container(
color: Theme.of(context).primaryColor,
color: Theme.of(context).accentColor,
padding: EdgeInsets.only(right: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
@@ -162,15 +238,16 @@ class DayHeaderDismissible extends StatelessWidget {
],
),
),
*/
background: Container(
color: Theme.of(context).accentColor,
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,
AppLocalizations.of(context)!.gymMode,
style: TextStyle(color: Colors.white),
),
Icon(
@@ -189,7 +266,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(),
),
],

View File

@@ -17,23 +17,21 @@
*/
import 'package:flutter/material.dart';
import 'package:wger/models/exercises/image.dart';
class ExerciseImage extends StatelessWidget {
const ExerciseImage({
Key key,
@required this.imageUrl,
@required this.serverUrl,
}) : super(key: key);
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(

View File

@@ -37,46 +37,45 @@ class WorkoutForm extends StatelessWidget {
WorkoutPlan _plan;
final _form = GlobalKey<FormState>();
WorkoutForm(
this._plan, {
Key key,
}) : super(key: key);
WorkoutForm(this._plan);
final TextEditingController workoutController = TextEditingController();
@override
Widget build(BuildContext context) {
workoutController.text = _plan.description ?? '';
if (_plan.id != null) {
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) {
return 'Please enter between $minLength and $maxLength characters.';
if (value!.isEmpty || value.length < minLength || value.length > maxLength) {
return AppLocalizations.of(context)!.enterCharacters(minLength, maxLength);
}
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 +111,9 @@ class _DayCheckboxState extends State<DayCheckbox> {
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 +128,11 @@ class _DayCheckboxState extends State<DayCheckbox> {
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,16 +151,16 @@ class _DayFormWidgetState extends State<DayFormWidget> {
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) {
return 'Please enter between $minLength and $maxLength characters.';
if (value!.isEmpty || value.length < minLength || value.length > maxLength) {
return AppLocalizations.of(context)!.enterCharacters(minLength, maxLength);
}
return null;
},
@@ -174,12 +169,12 @@ class _DayFormWidgetState extends State<DayFormWidget> {
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<WorkoutPlans>(context, listen: false).addDay(
@@ -217,11 +212,10 @@ class _DayFormWidgetState extends State<DayFormWidget> {
class SetFormWidget extends StatefulWidget {
Day _day;
Set _set;
late 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._set = set ?? Set.withData(day: _day.id, sets: 4);
}
@override
@@ -247,189 +241,248 @@ class _SetFormWidgetState extends State<SetFormWidget> {
void addExercise(Exercise exercise) {
setState(() {
widget._set.addExercise(exercise);
addSettings();
});
}
/// 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.order = order;
setting.setExercise(exercise);
setting.setRepetitionUnit(
Provider.of<WorkoutPlans>(context, listen: false).defaultRepetitionUnit,
);
setting.setWeightUnit(
Provider.of<WorkoutPlans>(context, listen: false).defaultWeightUnit,
);
widget._set.settings.add(setting);
}
}
}
@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<Exercises>(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<Auth>(context, listen: false).serverUrl;
final exercise = Provider.of<Exercises>(context, listen: false)
.findById(suggestion['data']['id']);
return ListTile(
leading: Container(
width: 45,
child: suggestion['data']['image'] != null
? ExerciseImage(
imageUrl: suggestion['data']['image'],
serverUrl: serverUrl,
)
: Container(),
),
title: Text(exercise.name),
subtitle: Text(exercise.category.name),
);
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
final exercise = Provider.of<Exercises>(context, listen: false)
.findById(suggestion['data']['id']);
addExercise(exercise);
},
validator: (value) {
if (value.isEmpty) {
return 'Please select an exercise';
}
return null;
},
return Form(
key: _formKey,
child: ListView(
children: [
TypeAheadFormField(
textFieldConfiguration: TextFieldConfiguration(
controller: this._exercisesController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.exercise,
helperMaxLines: 3,
helperText: AppLocalizations.of(context)!.selectExercises),
),
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();
suggestionsCallback: (pattern) async {
return await Provider.of<Exercises>(context, listen: false).searchExercise(pattern);
},
itemBuilder: (context, suggestion) {
final result = suggestion! as Map;
// Add all settings to list
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));
}
}
_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();
return ExerciseSetting(
exercise,
settings,
_detailed,
_currentSetSliderValue,
removeExercise,
String serverUrl = Provider.of<Auth>(context, listen: false).serverUrl!;
final exercise =
Provider.of<Exercises>(context, listen: false).findById(result['data']['id']);
return ListTile(
leading: Container(
width: 45,
child: ExerciseImageWidget(image: exercise.getMainImage),
),
title: Text(exercise.name),
subtitle: Text(
'${exercise.categoryObj.name} / ${exercise.equipment.map((e) => e.name).join(', ')}'),
);
}).toList(),
ElevatedButton(
child: Text(AppLocalizations.of(context).save),
onPressed: () async {
final isValid = _formKey.currentState.validate();
if (!isValid) {
return;
}
_formKey.currentState.save();
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
final result = suggestion! as Map;
final exercise =
Provider.of<Exercises>(context, listen: false).findById(result['data']['id']);
addExercise(exercise);
this._exercisesController.text = '';
},
validator: (value) {
if (widget._set.exercisesIds.length == 0) {
return AppLocalizations.of(context)!.selectExercise;
}
return null;
},
),
SizedBox(height: 10),
Center(
child: Text(AppLocalizations.of(context)!.nrOfSets(_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;
addSettings();
});
},
),
SwitchListTile(
title: Text(AppLocalizations.of(context)!.toggleDetails),
value: _detailed,
onChanged: (value) {
setState(() {
_detailed = !_detailed;
});
},
),
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();
final workoutProvider = Provider.of<WorkoutPlans>(context, listen: false);
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();
// Save set
Set setDb = await workoutProvider.addSet(widget._set);
widget._set.id = setDb.id;
final workoutProvider = Provider.of<WorkoutPlans>(context, listen: false);
// Remove unused settings
widget._set.settings.removeWhere((s) => s.weight == null && s.reps == null);
// Save set
Set setDb = await workoutProvider.addSet(widget._set);
widget._set.id = setDb.id;
// Save remaining settings
for (var setting in widget._set.settings) {
setting.setId = setDb.id;
// Remove unused settings
widget._set.settings.removeWhere((s) => s.weight == null && s.reps == null);
setting.weightUnit = setting.weightUnit ?? workoutProvider.defaultWeightUnit.id;
setting.repetitionUnit =
setting.repetitionUnit ?? workoutProvider.defaultRepetitionUnit.id;
setting.comment = '';
setting.repsText = 'temp text';
// Save remaining settings
for (var setting in widget._set.settings) {
setting.setId = setDb.id!;
setting.comment = '';
setting.repsText = 'temp text';
Setting settingDb = await workoutProvider.addSetting(setting);
setting.id = settingDb.id;
}
Setting settingDb = await workoutProvider.addSetting(setting);
setting.id = settingDb.id;
}
// Add to workout day
widget._day.sets.add(widget._set);
// 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;
int _numberOfSets;
final Exercise _exercise;
int _numberOfSets = 4;
bool _detailed;
Function removeExercise;
final Function removeExercise;
List<Setting> _settings = [];
ExerciseSetting(Exercise exercise, List<Setting> 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() {
Widget getRows(BuildContext context) {
List<Widget> 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(
@@ -441,27 +494,27 @@ class ExerciseSetting extends StatelessWidget {
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(height: 15),
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),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text('Reps'),
if (_detailed) Text('Unit'),
Text('Weight'),
if (_detailed) Text('Weight unit'),
if (_detailed) Text('RiR'),
],
),
getRow(),
if (!_detailed)
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(AppLocalizations.of(context)!.repetitions),
Text(AppLocalizations.of(context)!.weight),
],
),
getRows(context),
],
);
}
@@ -469,56 +522,77 @@ class ExerciseSetting extends StatelessWidget {
class RepsInputWidget extends StatelessWidget {
final _repsController = TextEditingController();
Setting _setting;
final Setting _setting;
final bool _detailed;
RepsInputWidget(Setting setting) {
this._setting = 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(Setting setting) {
this._setting = 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({Key key}) : super(key: key);
final Setting _setting;
RiRInputWidget(this._setting);
@override
_RiRInputWidgetState createState() => _RiRInputWidgetState();
@@ -529,19 +603,16 @@ class _RiRInputWidgetState extends State<RiRInputWidget> {
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
return DropdownButtonFormField(
decoration: InputDecoration(labelText: AppLocalizations.of(context)!.rir),
value: dropdownValue,
underline: Container(
height: 0,
//color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue;
dropdownValue = newValue!;
widget._setting.setRir(newValue);
});
},
items: <String>['1', '1.5', '2', '2.5', '3', '3.5']
.map<DropdownMenuItem<String>>((String value) {
items: Setting.possibleValues.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
@@ -552,26 +623,26 @@ class _RiRInputWidgetState extends State<RiRInputWidget> {
}
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<WeightUnitInputWidget> {
WeightUnit dropdownValue;
@override
Widget build(BuildContext context) {
return DropdownButton<WeightUnit>(
value: dropdownValue,
underline: Container(
height: 0,
// color: Colors.deepPurpleAccent,
),
onChanged: (WeightUnit newValue) {
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<WorkoutPlans>(context, listen: false)
@@ -579,10 +650,7 @@ class _WeightUnitInputWidgetState extends State<WeightUnitInputWidget> {
.map<DropdownMenuItem<WeightUnit>>((WeightUnit value) {
return DropdownMenuItem<WeightUnit>(
value: value,
child: Text(
value.name,
style: TextStyle(fontSize: 12),
),
child: Text(value.name),
);
}).toList(),
);
@@ -590,26 +658,26 @@ class _WeightUnitInputWidgetState extends State<WeightUnitInputWidget> {
}
class RepetitionUnitInputWidget extends StatefulWidget {
RepetitionUnitInputWidget({Key key}) : super(key: key);
final Setting _setting;
RepetitionUnitInputWidget(this._setting);
@override
_RepetitionUnitInputWidgetState createState() => _RepetitionUnitInputWidgetState();
}
class _RepetitionUnitInputWidgetState extends State<RepetitionUnitInputWidget> {
RepetitionUnit dropdownValue;
@override
Widget build(BuildContext context) {
return DropdownButton<RepetitionUnit>(
value: dropdownValue,
underline: Container(
height: 0,
// color: Colors.deepPurpleAccent,
),
onChanged: (RepetitionUnit newValue) {
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<WorkoutPlans>(context, listen: false)
@@ -617,10 +685,7 @@ class _RepetitionUnitInputWidgetState extends State<RepetitionUnitInputWidget> {
.map<DropdownMenuItem<RepetitionUnit>>((RepetitionUnit value) {
return DropdownMenuItem<RepetitionUnit>(
value: value,
child: Text(
value.name,
style: TextStyle(fontSize: 12),
),
child: Text(value.name),
);
}).toList(),
);

View File

@@ -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(
@@ -168,12 +160,12 @@ class LogPage extends StatelessWidget {
}
if (_setting.rir != null) {
_rirController.text = _setting.rir;
_rirController.text = _setting.rir!;
}
_log.date = DateTime.now();
_log.exercise = _exercise.id;
_log.workoutPlan = _workoutPlan.id;
_log.workoutPlan = _workoutPlan.id!;
_log.repetitionUnit = 1;
_log.weightUnit = 1;
}
@@ -192,49 +184,48 @@ class LogPage extends StatelessWidget {
style: Theme.of(context).textTheme.headline5,
),
),
Expanded(
child: Form(
key: _form,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
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).repetitions),
controller: _repsController,
keyboardType: TextInputType.number,
onFieldSubmitted: (_) {},
onSaved: (newValue) {
_log.reps = int.parse(newValue);
},
validator: (value) {
try {
double.parse(value);
} catch (error) {
return 'Please enter a valid number';
}
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),
decoration: InputDecoration(labelText: AppLocalizations.of(context)!.comment),
controller: _commentController,
keyboardType: TextInputType.multiline,
maxLines: 3,
@@ -245,34 +236,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<WorkoutPlans>(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<WorkoutPlans>(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 +335,100 @@ class _SessionPageState extends State<SessionPage> {
style: Theme.of(context).textTheme.headline5,
),
),
Expanded(
child: Form(
key: _form,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FormField<int>(
builder: (FormFieldState<int> state) {
return InputDecorator(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).impression,
Expanded(child: Container()),
Form(
key: _form,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FormField<int>(
builder: (FormFieldState<int> state) {
return InputDecorator(
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.impression,
),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: impressionValue,
isDense: true,
onChanged: (int? newValue) {
setState(() {
impressionValue = newValue!;
state.didChange(newValue);
});
},
items: ImpressionMap.keys.map<DropdownMenuItem<int>>((int key) {
return DropdownMenuItem<int>(
value: key,
child: Text(
ImpressionMap[key]!,
),
);
}).toList(),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: impressionValue,
isDense: true,
onChanged: (int newValue) {
setState(() {
impressionValue = newValue;
state.didChange(newValue);
});
},
items: ImpressionMap.keys.map<DropdownMenuItem<int>>((int key) {
return DropdownMenuItem<int>(
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<WorkoutPlans>(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 {
await Provider.of<WorkoutPlans>(context, listen: false).addSession(_session);
Navigator.of(context).pop();
} on WgerHttpException catch (error) {
showHttpExceptionErrorDialog(error, context);
} catch (error) {
showErrorDialog(error, context);
}
},
),
],
),
),
IconButton(
@@ -468,7 +455,7 @@ class TimerWidget extends StatefulWidget {
class _TimerWidgetState extends State<TimerWidget> {
// 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);

Some files were not shown because too many files have changed in this diff Show More