Merge branch 'feature/offline-mode' into feat/nutrition-ingredients-implementation

This commit is contained in:
Roland Geider
2026-05-21 13:01:26 +02:00
156 changed files with 9097 additions and 7077 deletions

View File

@@ -0,0 +1,32 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2020 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:drift/drift.dart';
import 'package:wger/models/exercises/image.dart';
/// Maps an [ExerciseImageStyle] to and from the Django wire format
/// (`'1'`–`'5'`).
class ExerciseImageStyleConverter extends TypeConverter<ExerciseImageStyle, String> {
const ExerciseImageStyleConverter();
@override
ExerciseImageStyle fromSql(String fromDb) => ExerciseImageStyle.fromWire(fromDb);
@override
String toSql(ExerciseImageStyle value) => value.wireValue;
}

View File

@@ -21,17 +21,18 @@ import 'package:drift_sqlite_async/drift_sqlite_async.dart';
import 'package:flutter/material.dart' show TimeOfDay;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:powersync/powersync.dart' as ps;
import 'package:wger/database/converters/exercise_image_style_converter.dart';
import 'package:wger/database/converters/time_of_day_converter.dart';
import 'package:wger/database/converters/workout_impression_converter.dart';
import 'package:wger/models/body_weight/weight_entry.dart';
import 'package:wger/models/core/language.dart';
import 'package:wger/models/core/license.dart';
import 'package:wger/models/exercises/alias.dart';
import 'package:wger/models/exercises/category.dart';
import 'package:wger/models/exercises/comment.dart';
import 'package:wger/models/exercises/equipment.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/image.dart';
import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/models/exercises/translation.dart';
import 'package:wger/models/exercises/video.dart';
import 'package:wger/models/gallery/image.dart';
import 'package:wger/models/measurements/measurement_category.dart';
@@ -71,6 +72,8 @@ part 'database.g.dart';
// Exercises
ExerciseTable,
ExerciseTranslationTable,
ExerciseAliasTable,
ExerciseCommentTable,
MuscleTable,
ExerciseMuscleM2N,
ExerciseSecondaryMuscleM2N,

File diff suppressed because it is too large Load Diff

View File

@@ -37,6 +37,7 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
logger: attachedLogger,
);
await db.initialize();
await _createRawTables(db);
final baseProvider = ref.read(wgerBaseProvider);
connectPowerSync(db, baseProvider.serverUrl!);
@@ -45,6 +46,71 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
return db;
}
/// Materialise the native SQLite tables for the raw entries declared in
/// [schema]. PowerSync only manages the JSON view tables itself, so any
/// `RawTable` entry must have its `CREATE TABLE`/`CREATE INDEX` statements
/// applied by us.
///
/// Skips all work when the raw tables already exist, so warm restarts don't
/// take a write lock on the DB.
Future<void> _createRawTables(PowerSyncDatabase db) async {
// Not STRICT: keep SQLite's type affinity behaviour so PowerSync's
// inferred inserts can bind values as they arrive from the JSON wire
// protocol without us having to coerce types up front.
const rawTables = ['exercises_exercise', 'exercises_translation'];
final existing = await db.getAll(
'SELECT name FROM sqlite_master '
'WHERE type = ? AND name IN (${rawTables.map((_) => '?').join(', ')})',
['table', ...rawTables],
);
if (existing.length == rawTables.length) {
return;
}
await db.writeTransaction((tx) async {
await tx.execute('''
CREATE TABLE IF NOT EXISTS exercises_exercise(
id TEXT NOT NULL PRIMARY KEY,
uuid TEXT,
category_id INTEGER,
variation_group TEXT,
created TEXT,
last_update TEXT
)
''');
await tx.execute(
'CREATE INDEX IF NOT EXISTS exercises_exercise__category '
'ON exercises_exercise(category_id)',
);
await tx.execute(
'CREATE INDEX IF NOT EXISTS exercises_exercise__variation '
'ON exercises_exercise(variation_group)',
);
await tx.execute('''
CREATE TABLE IF NOT EXISTS exercises_translation(
id TEXT NOT NULL PRIMARY KEY,
uuid TEXT,
language_id INTEGER,
exercise_id INTEGER,
description TEXT,
name TEXT,
created TEXT,
last_update TEXT
)
''');
await tx.execute(
'CREATE INDEX IF NOT EXISTS exercises_translation__language '
'ON exercises_translation(language_id)',
);
await tx.execute(
'CREATE INDEX IF NOT EXISTS exercises_translation__exercise '
'ON exercises_translation(exercise_id)',
);
});
}
/// Creates a fresh [DjangoConnector] for [baseUrl] and connects [db] to it.
/// Used both at initial creation and after a logout/login cycle to pick up
/// the new user's server URL / credentials.

View File

@@ -46,7 +46,7 @@ final class PowerSyncInstanceProvider
}
}
String _$powerSyncInstanceHash() => r'25fdd0cce6fad18d2859035f1d5475caac992dfb';
String _$powerSyncInstanceHash() => r'308719fe4d1af01353373f8dac86a2b64da840a7';
@ProviderFor(didCompleteSync)
final didCompleteSyncProvider = DidCompleteSyncFamily._();

View File

@@ -18,17 +18,18 @@
import 'package:drift/drift.dart';
import 'package:powersync/powersync.dart' as ps;
import 'package:wger/database/converters/exercise_image_style_converter.dart';
import 'package:wger/models/exercises/alias.dart';
import 'package:wger/models/exercises/category.dart';
import 'package:wger/models/exercises/comment.dart';
import 'package:wger/models/exercises/equipment.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/image.dart';
import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/models/exercises/translation.dart';
import 'package:wger/models/exercises/video.dart';
import 'language.dart';
@UseRowClass(Exercise)
@DataClassName('ExerciseRow')
class ExerciseTable extends Table {
@override
String get tableName => 'exercises_exercise';
@@ -42,22 +43,17 @@ class ExerciseTable extends Table {
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
}
const PowersyncExerciseTable = ps.Table(
'exercises_exercise',
[
ps.Column.text('uuid'),
ps.Column.integer('category_id'),
ps.Column.text('variation_group'),
ps.Column.text('created'),
ps.Column.text('last_update'),
],
indexes: [
ps.Index('category', [ps.IndexedColumn('category_id')]),
ps.Index('variation', [ps.IndexedColumn('variation_group')]),
],
/// Raw table: native SQLite storage instead of the default JSON-view layer.
/// Exercises are server-owned (read-only on the client) and dominate the
/// per-row JSON decode cost, so bypassing the view layer is the lever with
/// the biggest impact. The actual `CREATE TABLE` + `CREATE INDEX` statements
/// live next to `PowerSyncDatabase.initialize()` in `database/powersync/powersync.dart`.
const PowersyncExerciseTable = ps.RawTable.inferred(
name: 'exercises_exercise',
schema: ps.RawTableSchema(),
);
@UseRowClass(Translation)
@DataClassName('ExerciseTranslationRow')
class ExerciseTranslationTable extends Table {
@override
String get tableName => 'exercises_translation';
@@ -72,20 +68,58 @@ class ExerciseTranslationTable extends Table {
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
}
const PowersyncTranslationTable = ps.Table(
'exercises_translation',
/// See [PowersyncExerciseTable]: translations live in the same raw-table
/// store for the same reason (2k+ rows, wide text columns).
const PowersyncTranslationTable = ps.RawTable.inferred(
name: 'exercises_translation',
schema: ps.RawTableSchema(),
);
@UseRowClass(Alias)
class ExerciseAliasTable extends Table {
@override
String get tableName => 'exercises_alias';
IntColumn get id => integer()();
TextColumn get uuid => text()();
IntColumn get translationId =>
integer().named('translation_id').references(ExerciseTranslationTable, #id)();
TextColumn get alias => text()();
}
const PowersyncExerciseAliasTable = ps.Table(
'exercises_alias',
[
ps.Column.text('uuid'),
ps.Column.integer('language_id'),
ps.Column.integer('exercise_id'),
ps.Column.text('description'),
ps.Column.text('name'),
ps.Column.text('created'),
ps.Column.text('last_update'),
ps.Column.integer('translation_id'),
ps.Column.text('alias'),
],
indexes: [
ps.Index('language', [ps.IndexedColumn('language_id')]),
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
ps.Index('translation', [ps.IndexedColumn('translation_id')]),
],
);
@UseRowClass(Comment)
class ExerciseCommentTable extends Table {
@override
String get tableName => 'exercises_exercisecomment';
IntColumn get id => integer()();
TextColumn get uuid => text()();
IntColumn get translationId =>
integer().named('translation_id').references(ExerciseTranslationTable, #id)();
TextColumn get comment => text()();
}
const PowersyncExerciseCommentTable = ps.Table(
'exercises_exercisecomment',
[
ps.Column.text('uuid'),
ps.Column.integer('translation_id'),
ps.Column.text('comment'),
],
indexes: [
ps.Index('translation', [ps.IndexedColumn('translation_id')]),
],
);
@@ -215,6 +249,22 @@ class ExerciseImageTable extends Table {
// Relative path under MEDIA_ROOT (Django's ImageField stores this)
TextColumn get image => text()();
BoolColumn get isMain => boolean().named('is_main')();
BoolColumn get isAiGenerated => boolean().named('is_ai_generated')();
TextColumn get style => text().map(const ExerciseImageStyleConverter())();
IntColumn get width => integer().nullable()();
IntColumn get height => integer().nullable()();
DateTimeColumn get created => dateTime()();
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
// License (TASL — Title / Author / Source / License). license_author may be
// null on the server (TextField with null=True); the others are not-null
// strings (possibly empty) on the server.
IntColumn get licenseId => integer().named('license_id')();
TextColumn get licenseTitle => text().named('license_title')();
TextColumn get licenseObjectUrl => text().named('license_object_url')();
TextColumn get licenseAuthor => text().named('license_author').nullable()();
TextColumn get licenseAuthorUrl => text().named('license_author_url')();
TextColumn get licenseDerivativeSourceUrl => text().named('license_derivative_source_url')();
}
const PowersyncExerciseImageTable = ps.Table(
@@ -224,9 +274,22 @@ const PowersyncExerciseImageTable = ps.Table(
ps.Column.integer('exercise_id'),
ps.Column.text('image'),
ps.Column.integer('is_main'),
ps.Column.integer('is_ai_generated'),
ps.Column.text('style'),
ps.Column.integer('width'),
ps.Column.integer('height'),
ps.Column.text('created'),
ps.Column.text('last_update'),
ps.Column.integer('license_id'),
ps.Column.text('license_title'),
ps.Column.text('license_object_url'),
ps.Column.text('license_author'),
ps.Column.text('license_author_url'),
ps.Column.text('license_derivative_source_url'),
],
indexes: [
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
ps.Index('license', [ps.IndexedColumn('license_id')]),
],
);
@@ -238,6 +301,7 @@ class ExerciseVideoTable extends Table {
IntColumn get id => integer()();
TextColumn get uuid => text()();
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
BoolColumn get isMain => boolean().named('is_main')();
TextColumn get url => text()();
IntColumn get size => integer()();
IntColumn get duration => integer()();
@@ -245,8 +309,18 @@ class ExerciseVideoTable extends Table {
IntColumn get height => integer()();
TextColumn get codec => text()();
TextColumn get codecLong => text().named('codec_long')();
DateTimeColumn get created => dateTime()();
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
// License (TASL — Title / Author / Source / License). license_author may be
// null on the server (TextField with null=True); the others are not-null
// strings (possibly empty) on the server.
IntColumn get licenseId => integer().named('license_id')();
TextColumn get licenseAuthor => text().named('license_author')();
TextColumn get licenseTitle => text().named('license_title')();
TextColumn get licenseObjectUrl => text().named('license_object_url')();
TextColumn get licenseAuthor => text().named('license_author').nullable()();
TextColumn get licenseAuthorUrl => text().named('license_author_url')();
TextColumn get licenseDerivativeSourceUrl => text().named('license_derivative_source_url')();
}
const PowersyncExerciseVideoTable = ps.Table(
@@ -254,6 +328,7 @@ const PowersyncExerciseVideoTable = ps.Table(
[
ps.Column.text('uuid'),
ps.Column.integer('exercise_id'),
ps.Column.integer('is_main'),
ps.Column.text('url'),
ps.Column.integer('size'),
ps.Column.integer('duration'),
@@ -261,10 +336,17 @@ const PowersyncExerciseVideoTable = ps.Table(
ps.Column.integer('height'),
ps.Column.text('codec'),
ps.Column.text('codec_long'),
ps.Column.text('created'),
ps.Column.text('last_update'),
ps.Column.integer('license_id'),
ps.Column.text('license_title'),
ps.Column.text('license_object_url'),
ps.Column.text('license_author'),
ps.Column.text('license_author_url'),
ps.Column.text('license_derivative_source_url'),
],
indexes: [
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
ps.Index('license', [ps.IndexedColumn('license_id')]),
],
);

View File

@@ -106,10 +106,15 @@ class IngredientImageTable extends Table {
// Relative path under MEDIA_ROOT (Django's ImageField stores this)
TextColumn get image => text()();
IntColumn get size => integer()();
IntColumn get width => integer()();
IntColumn get height => integer()();
DateTimeColumn get created => dateTime()();
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
// License information
// License (TASL). license_author may be null on the server (TextField with
// null=True); the others are not-null strings (possibly empty).
IntColumn get licenseId => integer().named('license_id')();
TextColumn get author => text().named('license_author')();
TextColumn get author => text().named('license_author').nullable()();
TextColumn get authorUrl => text().named('license_author_url')();
TextColumn get title => text().named('license_title')();
TextColumn get objectUrl => text().named('license_object_url')();
@@ -123,6 +128,10 @@ const PowersyncIngredientImageTable = ps.Table(
ps.Column.integer('ingredient_id'),
ps.Column.text('image'),
ps.Column.integer('size'),
ps.Column.integer('width'),
ps.Column.integer('height'),
ps.Column.text('created'),
ps.Column.text('last_update'),
ps.Column.integer('license_id'),
ps.Column.text('license_author'),
ps.Column.text('license_author_url'),

View File

@@ -56,6 +56,7 @@ const PREFS_INGREDIENTS = 'ingredientData';
const PREFS_WORKOUT_UNITS = 'workoutUnits';
const PREFS_USER = 'userData';
const PREFS_USER_DARK_THEME = 'userDarkMode';
const PREFS_USER_LOCALE = 'userLocale';
const PREFS_LAST_SERVER = 'lastServer';
/// True once PowerSync has been reachable for this user at least once
@@ -128,6 +129,9 @@ const GITHUB_REPO_URL = '$GITHUB_PROJECT_URL/flutter';
const GITHUB_ISSUES_URL = '$GITHUB_REPO_URL/issues/new/choose';
const GITHUB_ISSUES_BUG_URL = '$GITHUB_REPO_URL/issues/new?template=1_bug.yml';
const GITHUB_SPONSORS_URL = 'https://github.com/sponsors/wger-project';
/// Maximum length for a pre-filled GitHub issue URL
const GITHUB_ISSUES_MAX_URL_LENGTH = 8000;
const DISCORD_URL = 'https://discord.gg/rPWFv6W';
const MASTODON_URL = 'https://fosstodon.org/@wger';
const READTHEDOCS_URL = 'https://wger.readthedocs.io';

View File

@@ -24,6 +24,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
import 'package:logging/logging.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -36,6 +37,24 @@ import 'package:wger/providers/workout_logs_notifier.dart';
import 'consts.dart';
import 'logs.dart';
/// Whether an error dialog is currently on screen.
///
/// Errors can fire in quick succession; this guards against stacking several
/// modal dialogs on top of each other.
bool _errorDialogVisible = false;
/// How an error should be surfaced to the user.
enum ErrorSeverity {
/// Logged only; not worth interrupting the user (e.g. layout overflows).
cosmetic,
/// A brief, non-blocking snackbar (e.g. transient connectivity problems).
transient,
/// A blocking error dialog.
fatal,
}
void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? context}) {
final logger = Logger('showHttpExceptionErrorDialog');
@@ -51,6 +70,12 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? co
return;
}
if (_errorDialogVisible) {
logger.info('Suppressing error dialog, one is already visible: $exception');
return;
}
_errorDialogVisible = true;
showDialog(
context: dialogContext,
builder: (ctx) => AlertDialog(
@@ -76,7 +101,7 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? co
),
],
),
);
).whenComplete(() => _errorDialogVisible = false);
}
void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext? context}) {
@@ -85,7 +110,7 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext
// of a widget's build method.
final BuildContext? dialogContext = context ?? navigatorKey.currentContext;
final logger = Logger('showHttpExceptionErrorDialog');
final logger = Logger('showGeneralErrorDialog');
if (dialogContext == null) {
if (kDebugMode) {
@@ -94,32 +119,24 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext
return;
}
if (_errorDialogVisible) {
logger.info('Suppressing error dialog, one is already visible: $error');
return;
}
_errorDialogVisible = true;
final i18n = AppLocalizations.of(dialogContext);
// If possible, determine the error title and message based on the error type.
// If possible, determine the issue title and message based on the error type.
// (Note that issue titles and error messages are not localized)
bool allowReportIssue = true;
String issueTitle = 'An error occurred';
String issueErrorMessage = error.toString();
String errorTitle = i18n.anErrorOccurred;
String errorDescription = i18n.errorInfoDescription;
var icon = Icons.error;
if (error is TimeoutException) {
issueTitle = 'Network Timeout';
issueErrorMessage =
'The connection to the server timed out. Please check your '
'internet connection and try again.';
} else if (error is FlutterErrorDetails) {
if (error is FlutterErrorDetails) {
issueTitle = 'Application Error';
issueErrorMessage = error.exceptionAsString();
} else if (error is MissingRequiredKeysException) {
issueTitle = 'Missing Required Key';
} else if (error is SocketException) {
allowReportIssue = false;
icon = Icons.signal_wifi_connected_no_internet_4_outlined;
errorTitle = i18n.errorCouldNotConnectToServer;
errorDescription = i18n.errorCouldNotConnectToServerDetails;
}
final String fullStackTrace = stackTrace?.toString() ?? 'No stack trace available.';
@@ -134,16 +151,19 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext
spacing: 8,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: Theme.of(context).colorScheme.error),
Icon(Icons.error, color: Theme.of(context).colorScheme.error),
Expanded(
child: Text(errorTitle, style: TextStyle(color: Theme.of(context).colorScheme.error)),
child: Text(
i18n.anErrorOccurred,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
],
),
content: SingleChildScrollView(
child: ListBody(
children: [
Text(errorDescription),
Text(i18n.errorInfoDescription),
const SizedBox(height: 8),
Text(i18n.errorInfoDescription2),
const SizedBox(height: 10),
@@ -198,42 +218,29 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext
),
),
actions: [
if (allowReportIssue)
TextButton(
child: const Text('Report issue'),
onPressed: () async {
final logText = applicationLogs.isEmpty
? '-- No logs available --'
: applicationLogs.join('\n');
final description = Uri.encodeComponent(
'## Description\n\n'
'[Please describe what you were doing when the error occurred.]\n\n'
'## Error details\n\n'
'Error title: $issueTitle\n'
'Error message: $issueErrorMessage\n'
'Stack trace:\n'
'```\n$stackTrace\n```\n\n'
'App logs (last ${applicationLogs.length} entries):\n'
'```\n$logText\n```',
);
final githubIssueUrl =
'$GITHUB_ISSUES_BUG_URL'
'&title=$issueTitle'
'&description=$description';
final Uri reportUri = Uri.parse(githubIssueUrl);
TextButton(
child: const Text('Report issue'),
onPressed: () async {
final githubIssueUrl = buildGithubIssueUrl(
issueTitle: issueTitle,
issueErrorMessage: issueErrorMessage,
stackTrace: fullStackTrace,
applicationLogs: applicationLogs,
);
final Uri reportUri = Uri.parse(githubIssueUrl);
try {
await launchUrl(reportUri, mode: LaunchMode.externalApplication);
} catch (e) {
if (kDebugMode) {
logger.warning('Error launching URL: $e');
}
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Error opening issue tracker: $e')));
try {
await launchUrl(reportUri, mode: LaunchMode.externalApplication);
} catch (e) {
if (kDebugMode) {
logger.warning('Error launching URL: $e');
}
},
),
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Error opening issue tracker: $e')));
}
},
),
FilledButton(
child: Text(MaterialLocalizations.of(context).okButtonLabel),
onPressed: () {
@@ -243,7 +250,101 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext
],
);
},
);
).whenComplete(() => _errorDialogVisible = false);
}
/// Classifies [error] to decide how it should be surfaced.
ErrorSeverity classifyError(Object? error) {
// Flutter reports layout overflows as a plain FlutterError without a
// dedicated type, so matching the message is the only option.
final isLayoutOverflow = error is FlutterError && error.toString().contains('overflowed');
if (error is NetworkImageLoadException || isLayoutOverflow) {
return ErrorSeverity.cosmetic;
}
if (error is SocketException || error is http.ClientException || error is TimeoutException) {
return ErrorSeverity.transient;
}
return ErrorSeverity.fatal;
}
/// Routes [error] to the appropriate UI based on its [ErrorSeverity].
///
/// The caller is responsible for logging the error beforehand.
void handleError(Object? error, StackTrace? stackTrace) {
switch (classifyError(error)) {
case ErrorSeverity.cosmetic:
break;
case ErrorSeverity.transient:
showTransientErrorSnackbar();
case ErrorSeverity.fatal:
if (error is WgerHttpException) {
showHttpExceptionErrorDialog(error);
} else {
showGeneralErrorDialog(error, stackTrace);
}
}
}
/// Shows a brief, non-blocking snackbar telling the user about a (hopefully)
/// transient error such as network problems, etc.
void showTransientErrorSnackbar() {
final messenger = scaffoldMessengerKey.currentState;
final context = navigatorKey.currentContext;
if (messenger == null || context == null) {
if (kDebugMode) {
Logger(
'showNetworkErrorSnackbar',
).warning('Could not show snackbar: no messenger or context available.');
}
return;
}
messenger
..clearSnackBars()
..showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context).errorCouldNotConnectToServer)),
);
}
/// Builds the URL that opens a pre-filled GitHub bug report.
///
/// The error details are passed to GitHub as query parameters and since
/// GitHub rejects URLs longer than [GITHUB_ISSUES_MAX_URL_LENGTH], when
/// the report would exceed that limit, the oldest log entries are pruned
/// until the URL fits.
String buildGithubIssueUrl({
required String issueTitle,
required String issueErrorMessage,
required String stackTrace,
required List<String> applicationLogs,
}) {
String composeUrl(List<String> logs) {
final logText = logs.isEmpty ? '-- No logs available --' : logs.join('\n');
final description =
'## Description\n\n'
'[Please describe what you were doing when the error occurred.]\n\n'
'## Error details\n\n'
'Error title: $issueTitle\n'
'Error message: $issueErrorMessage\n'
'Stack trace:\n```\n$stackTrace\n```\n\n'
'App logs (last ${logs.length} entries):\n```\n$logText\n```';
return '$GITHUB_ISSUES_BUG_URL'
'&title=${Uri.encodeComponent(issueTitle)}'
'&description=${Uri.encodeComponent(description)}';
}
// The logs come newest-first, so the oldest entry is the last one. Drop it
// and retry until the URL fits within the limit.
var logs = applicationLogs;
while (true) {
final url = composeUrl(logs);
if (url.length <= GITHUB_ISSUES_MAX_URL_LENGTH || logs.isEmpty) {
return url;
}
logs = logs.sublist(0, logs.length - 1);
}
}
/// A widget to render HTML errors returned by the server

View File

@@ -34,3 +34,19 @@ Locale? resolveLocale(List<Locale>? locales, Iterable<Locale> supportedLocales)
}
return null;
}
/// Stable string encoding for a [Locale], matching the keys generated by
/// Flutter's AppLocalizations (e.g. `pt_BR`, `zh_Hant`, `pl`). [scriptCode]
/// takes precedence over [countryCode] so locales like `zh_Hant` round-trip
/// distinctly from plain `zh`.
String encodeLocale(Locale locale) {
final script = locale.scriptCode;
if (script != null && script.isNotEmpty) {
return '${locale.languageCode}_$script';
}
final country = locale.countryCode;
if (country != null && country.isNotEmpty) {
return '${locale.languageCode}_$country';
}
return locale.languageCode;
}

File diff suppressed because it is too large Load Diff

View File

@@ -969,11 +969,8 @@
},
"superset": "Superset",
"isVegan": "Vegan",
"@isVegan": {},
"isVegetarian": "Vegetarisch",
"@isVegetarian": {},
"filter": "Filtern",
"@filter": {},
"searchLanguageCurrent": "Nur aktuelle Sprache ({lang})",
"@searchLanguageCurrent": {
"type": "text",
@@ -993,5 +990,17 @@
}
},
"searchLanguageAll": "Alle Sprachen",
"@searchLanguageAll": {}
"dashboardWidgets": "Dashboard Widgets",
"slotEntryTypeWarmup": "Aufwärmtraining",
"trophies": "Trophäen",
"topSet": "Höchster Satz: {value}",
"@topSet": {
"description": "Value is a representation of the set, like '10 x 80kg'",
"type": "text",
"placeholders": {
"value": {
"type": "String"
}
}
}
}

View File

@@ -1183,6 +1183,14 @@
"networkInfo": "Network information",
"youAreOffline": "You are offline",
"offlineModeInfo": "Some features are unavailable until you reconnect to the internet (buttons and menus will be disabled). Currently, this mainly affects editing routines and nutrition plans, but logging workouts and meals works offline. The data will be synced automatically once you are back online.",
"appLanguage": "App language",
"@appLanguage": {
"description": "Label for the in-app language selector in settings"
},
"appLanguageSystem": "System default",
"@appLanguageSystem": {
"description": "Dropdown entry that follows the device system language"
},
"productNotFoundOpenFoodFacts": "You can add this product to Open Food Facts to help the community!",
"@productNotFoundOpenFoodFacts": {
"description": "Label shown when product is not found to encourage users to go on Open Food Facts and add it themselves"

View File

@@ -994,5 +994,8 @@
"dashboardWidgets": "Widgets del panel",
"trophies": "Trofeos",
"personalRecords": "Registros personales",
"noTrophies": "No tienes trofeos todavía"
"noTrophies": "No tienes trofeos todavía",
"slotEntryTypeWarmup": "Calentamiento",
"preview": "Vista previa",
"serverUpdateTitle": "Actualización de servidor requerida"
}

1
lib/l10n/app_gl.arb Normal file
View File

@@ -0,0 +1 @@
{}

View File

@@ -1126,5 +1126,64 @@
"type": "String"
}
}
},
"preview": "Pregledaj",
"filterNutriscore": "Nutri-Score filtar",
"@filterNutriscore": {
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"
},
"filterNutriscoreOff": "Isključeno",
"@filterNutriscoreOff": {
"description": "Label for the first slider stop, which disables the Nutri-Score filter"
},
"filterNutriscoreNoFilter": "Bez filtra",
"@filterNutriscoreNoFilter": {
"description": "Helper text shown under the Nutri-Score slider when it is at the Off position"
},
"filterNutriscoreOrBetter": "{grade} ili bolje",
"@filterNutriscoreOrBetter": {
"description": "Helper text shown under the Nutri-Score slider when a grade is selected (e.g. 'C or better')",
"placeholders": {
"grade": {
"type": "String",
"example": "C"
}
}
},
"serverConfigIssueTitle": "Problem s konfiguracijom servera",
"@serverConfigIssueTitle": {
"description": "Title of the dialog shown when server misconfiguration is detected"
},
"serverConfigIssueMessage": "Otkrivena je pogrešna konfiguracija servera, zaglavlja se ne prosljeđuju ispravno. Pogledaj dokumentaciju.",
"@serverConfigIssueMessage": {
"description": "Message explaining server misconfiguration and linking to documentation"
},
"understand": "Razumijem",
"@understand": {
"description": "Button label to acknowledge and dismiss the server configuration warning"
},
"viewDocumentation": "Prikaži dokumentaciju",
"@viewDocumentation": {
"description": "Button label to open the documentation about server configuration"
},
"slotEntryTypeWarmup": "Zagrijavanje",
"useBasicMarkdown": "Za formatiranje teksta se može koristiti osnovni Markdown",
"editorBold": "Podebljano",
"@editorBold": {
"description": "Label for bold formatting"
},
"editorItalic": "Kursiv",
"editorList": "Popis",
"exerciseSearchMode": "Modus pretrage",
"@exerciseSearchMode": {
"description": "Heading above the segmented control that lets the user pick between fuzzy and exact name matching"
},
"searchModeFuzzy": "Otprilike",
"@searchModeFuzzy": {
"description": "Label for the search mode that performs a fuzzy/substring search on exercise names"
},
"searchModeExact": "Točno",
"@searchModeExact": {
"description": "Label for the search mode that only matches exercises with this exact name"
}
}

View File

@@ -941,5 +941,8 @@
"applicationLogs": "Registri dell'applicazione",
"dayTypeCustom": "Personalizzato",
"dayTypeAfap": "Più velocemente possibile",
"dayTypeHiit": "Allenamento a intervalli ad alta intensità"
"dayTypeHiit": "Allenamento a intervalli ad alta intensità",
"workoutCompleted": "Allenamento Completato",
"noTrophies": "Non ci sono trofei",
"preview": "Anteprima"
}

View File

@@ -191,15 +191,15 @@
"@passwordsDontMatch": {
"description": "Error message when the user enters two different passwords during registration"
},
"invalidUrl": "Skriv inn en gyldig nettadresse",
"invalidUrl": "Skriv inn en gyldig nettadresse (URL)",
"@invalidUrl": {
"description": "Error message when the user enters an invalid URL, e.g. in the login form"
},
"useCustomServer": "Bruk egendefinert tjener",
"useCustomServer": "Bruk egendefinert server",
"@useCustomServer": {
"description": "Toggle button allowing users to switch between the default and a custom wger server"
},
"useDefaultServer": "Bruk forvalgt tjener",
"useDefaultServer": "Bruk standardserver",
"@useDefaultServer": {
"description": "Toggle button allowing users to switch between the default and a custom wger server"
},
@@ -229,7 +229,7 @@
"@value": {
"description": "The value of a measurement entry"
},
"userProfile": "Din Profil",
"userProfile": "Din profil",
"usernameValidChars": "Et brukernavn kan bare inneholde bokstaver, sifre og tegnene @,+,.,-, og _",
"@usernameValidChars": {
"description": "Error message when the user tries to register a username with forbidden characters"

View File

@@ -833,6 +833,8 @@
"darkMode": "Zawsze używaj trybu ciemnego",
"lightMode": "Zawsze używaj trybu jasnego",
"systemMode": "Ustawienia systemu",
"appLanguage": "Język aplikacji",
"appLanguageSystem": "Domyślny systemu",
"fitInWeek": "Dopasuj w tygodniu",
"dayTypeAmrap": "Tak dużo rund jak to możliwe",
"trophies": "Trofea",

View File

@@ -1040,5 +1040,64 @@
"type": "String"
}
}
},
"slotEntryTypeWarmup": "Mobilização geral",
"preview": "Ensaio",
"useBasicMarkdown": "Podes usar markdown básico para formatar o texto",
"editorBold": "Negrito",
"@editorBold": {
"description": "Label for bold formatting"
},
"editorItalic": "Itálico",
"editorList": "Lista",
"filterNutriscore": "Filtro Nutri-score",
"@filterNutriscore": {
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"
},
"filterNutriscoreOff": "Desligado",
"@filterNutriscoreOff": {
"description": "Label for the first slider stop, which disables the Nutri-Score filter"
},
"filterNutriscoreNoFilter": "Sem filtro",
"@filterNutriscoreNoFilter": {
"description": "Helper text shown under the Nutri-Score slider when it is at the Off position"
},
"filterNutriscoreOrBetter": "{grade} ou melhor",
"@filterNutriscoreOrBetter": {
"description": "Helper text shown under the Nutri-Score slider when a grade is selected (e.g. 'C or better')",
"placeholders": {
"grade": {
"type": "String",
"example": "C"
}
}
},
"viewDocumentation": "Ver documentação",
"@viewDocumentation": {
"description": "Button label to open the documentation about server configuration"
},
"exerciseSearchMode": "Modo de pesquisa",
"@exerciseSearchMode": {
"description": "Heading above the segmented control that lets the user pick between fuzzy and exact name matching"
},
"searchModeFuzzy": "Busca aproximada",
"@searchModeFuzzy": {
"description": "Label for the search mode that performs a fuzzy/substring search on exercise names"
},
"searchModeExact": "Busca exata",
"@searchModeExact": {
"description": "Label for the search mode that only matches exercises with this exact name"
},
"serverConfigIssueTitle": "Problema de configuração do servidor",
"@serverConfigIssueTitle": {
"description": "Title of the dialog shown when server misconfiguration is detected"
},
"serverConfigIssueMessage": "Configuração incorreta do servidor; os cabeçalhos não estão a ser transmitidos corretamente. Consulta a documentação.",
"@serverConfigIssueMessage": {
"description": "Message explaining server misconfiguration and linking to documentation"
},
"understand": "Entendo",
"@understand": {
"description": "Button label to acknowledge and dismiss the server configuration warning"
}
}

View File

@@ -167,7 +167,7 @@
"@pause": {
"description": "Noun, not an imperative! Label used for the pause when using the gym mode"
},
"success": "Bem sucedido",
"success": "Sucesso",
"@success": {
"description": "Message when an action completed successfully, usually used as a heading"
},
@@ -1126,5 +1126,72 @@
"type": "String"
}
}
},
"preview": "Pré-visualização",
"slotEntryTypeWarmup": "Aquecimento",
"useBasicMarkdown": "Você pode usar Markdown básico para formatar o texto",
"editorBold": "Audacioso",
"@editorBold": {
"description": "Label for bold formatting"
},
"editorItalic": "Itálico",
"editorList": "Lista",
"filterNutriscore": "Filtro Nutri-Score",
"@filterNutriscore": {
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"
},
"filterNutriscoreOff": "Desligado",
"@filterNutriscoreOff": {
"description": "Label for the first slider stop, which disables the Nutri-Score filter"
},
"filterNutriscoreNoFilter": "Sem filtro",
"@filterNutriscoreNoFilter": {
"description": "Helper text shown under the Nutri-Score slider when it is at the Off position"
},
"filterNutriscoreOrBetter": "{grade} ou melhor",
"@filterNutriscoreOrBetter": {
"description": "Helper text shown under the Nutri-Score slider when a grade is selected (e.g. 'C or better')",
"placeholders": {
"grade": {
"type": "String",
"example": "C"
}
}
},
"exerciseSearchMode": "Modo de pesquisa",
"@exerciseSearchMode": {
"description": "Heading above the segmented control that lets the user pick between fuzzy and exact name matching"
},
"searchModeFuzzy": "Busca aproximada",
"@searchModeFuzzy": {
"description": "Label for the search mode that performs a fuzzy/substring search on exercise names"
},
"searchModeExact": "Busca exata",
"@searchModeExact": {
"description": "Label for the search mode that only matches exercises with this exact name"
},
"serverConfigIssueTitle": "Problema de configuração do servidor",
"@serverConfigIssueTitle": {
"description": "Title of the dialog shown when server misconfiguration is detected"
},
"serverConfigIssueMessage": "Foi detectada uma configuração incorreta do servidor; os cabeçalhos não estão sendo transmitidos corretamente. Consulte a documentação.",
"@serverConfigIssueMessage": {
"description": "Message explaining server misconfiguration and linking to documentation"
},
"understand": "Eu entendo",
"@understand": {
"description": "Button label to acknowledge and dismiss the server configuration warning"
},
"viewDocumentation": "Ver documentação",
"@viewDocumentation": {
"description": "Button label to open the documentation about server configuration"
},
"appLanguage": "Idioma do aplicativo",
"@appLanguage": {
"description": "Label for the in-app language selector in settings"
},
"appLanguageSystem": "Padrão do sistema",
"@appLanguageSystem": {
"description": "Dropdown entry that follows the device system language"
}
}

15
lib/l10n/app_sn.arb Normal file
View File

@@ -0,0 +1,15 @@
{
"userProfile": "Profile Yako",
"login": "Pinda muApp",
"@login": {
"description": "Text for login button"
},
"logout": "Buda muApp",
"@logout": {
"description": "Text for logout button"
},
"register": "Kuzvinyoresa",
"@register": {
"description": "Text for registration button"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// Native display names for each supported locale, keyed by the locale name
const Map<String, String> languageNativeNames = {
'am': 'አማርኛ',
'ar': 'العربية',
'ca': 'Català',
'cs': 'Čeština',
'de': 'Deutsch',
'el': 'Ελληνικά',
'en': 'English',
'es': 'Español',
'fa': 'فارسی',
'fil': 'Filipino',
'fr': 'Français',
'gl': 'Galego',
'he': 'עברית',
'hi': 'हिन्दी',
'hr': 'Hrvatski',
'hu': 'Magyar',
'id': 'Bahasa Indonesia',
'it': 'Italiano',
'ja': '日本語',
'ko': '한국어',
'mk': 'Македонски',
'nb': 'Norsk bokmål',
'nl': 'Nederlands',
'pl': 'Polski',
'pt': 'Português',
'pt_BR': 'Português (Brasil)',
'pt_PT': 'Português (Portugal)',
'ro': 'Română',
'ru': 'Русский',
'sk': 'Slovenčina',
'sn': 'chiShona',
'ta': 'தமிழ்',
'th': 'ไทย',
'tr': 'Türkçe',
'uk': 'Українська',
'ur': 'اردو',
'zh': '中文',
'zh_Hant': '繁體中文',
};

View File

@@ -23,7 +23,6 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/helpers/errors.dart';
import 'package:wger/helpers/locale.dart';
import 'package:wger/helpers/shared_preferences.dart';
@@ -89,6 +88,7 @@ void _setupLogging() {
}
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
void main() async {
// Needs to be called before runApp
@@ -101,26 +101,14 @@ void main() async {
// SharedPreferences to SharedPreferencesAsync migration function
await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences();
// Catch errors from Flutter itself (widget build, layout, paint, etc.)
//
// NOTE: it seems this sometimes makes problems and even freezes the flutter
// process when widgets overflow, so it is disabled in dev mode.
if (!kDebugMode) {
FlutterError.onError = (FlutterErrorDetails details) {
final stack = details.stack ?? StackTrace.empty;
logger.severe('Error caught by FlutterError.onError: ${details.exception}');
FlutterError.dumpErrorToConsole(details);
// Don't show the full error dialog for network image loading errors.
if (details.exception is NetworkImageLoadException) {
return;
}
showGeneralErrorDialog(details.exception, stack);
// throw details.exception;
};
}
FlutterError.onError = (FlutterErrorDetails details) {
final stack = details.stack ?? StackTrace.empty;
logger.severe('Error caught by FlutterError.onError: ${details.exception}');
FlutterError.dumpErrorToConsole(details);
handleError(details.exception, stack);
};
// Catch errors that happen outside of the Flutter framework (e.g., in async operations)
PlatformDispatcher.instance.onError = (error, stack) {
@@ -135,11 +123,7 @@ void main() async {
logger.severe('Error caught by PlatformDispatcher.instance.onError: $error');
logger.severe('Stack trace: $stack');
if (error is WgerHttpException) {
showHttpExceptionErrorDialog(error);
} else {
showGeneralErrorDialog(error, stack);
}
handleError(error, stack);
// Return true to indicate that the error has been handled.
return true;
@@ -192,15 +176,20 @@ class MainApp extends ConsumerWidget {
final themeMode = ref.watch(
appSettingsProvider.select((s) => s.value?.themeMode ?? ThemeMode.system),
);
final userLocale = ref.watch(
appSettingsProvider.select((s) => s.value?.userLocale),
);
return MaterialApp(
title: 'wger',
navigatorKey: navigatorKey,
scaffoldMessengerKey: scaffoldMessengerKey,
theme: wgerLightTheme,
darkTheme: wgerDarkTheme,
highContrastTheme: wgerLightThemeHc,
highContrastDarkTheme: wgerDarkThemeHc,
themeMode: themeMode,
locale: userLocale,
home: _getHomeScreen(authState),
routes: {
DashboardScreen.routeName: (ctx) => const DashboardScreen(),

View File

@@ -27,79 +27,77 @@ import 'package:wger/models/exercises/translation.dart';
import 'package:wger/models/exercises/video.dart';
class Exercise extends Equatable {
final _logger = Logger('ExerciseModel');
static final _logger = Logger('ExerciseModel');
late final int id;
late final String uuid;
late final String? variationGroup;
late final DateTime? created;
late final DateTime? lastUpdate;
late final DateTime? lastUpdateGlobal;
late int categoryId;
final int id;
final String uuid;
final String? variationGroup;
final DateTime? created;
final DateTime? lastUpdate;
final ExerciseCategory category;
final List<Muscle> muscles;
final List<Muscle> musclesSecondary;
final List<Equipment> equipment;
final List<ExerciseImage> images;
final List<Translation> translations;
final List<Video> videos;
final List<String> authors;
final List<String> authorsGlobal;
ExerciseCategory? category;
List<int> musclesIds = [];
List<Muscle> muscles = [];
List<int> musclesSecondaryIds = [];
List<Muscle> musclesSecondary = [];
List<int> equipmentIds = [];
List<Equipment> equipment = [];
List<ExerciseImage> images = [];
List<Translation> translations = [];
List<Video> videos = [];
List<String> authors = [];
List<String> authorsGlobal = [];
int get categoryId => category.id;
List<int> get musclesIds => muscles.map((e) => e.id).toList();
List<int> get musclesSecondaryIds => musclesSecondary.map((e) => e.id).toList();
List<int> get equipmentIds => equipment.map((e) => e.id).toList();
Exercise({
const Exercise({
required this.id,
required this.uuid,
this.created,
this.lastUpdate,
this.variationGroup,
required this.categoryId,
required this.category,
this.muscles = const [],
this.musclesSecondary = const [],
this.equipment = const [],
this.images = const [],
this.translations = const [],
this.videos = const [],
this.authors = const [],
this.authorsGlobal = const [],
});
Exercise copyWith({
int? id,
String? uuid,
DateTime? created,
DateTime? lastUpdate,
String? variationGroup,
ExerciseCategory? category,
List<Muscle>? muscles,
List<Muscle>? musclesSecondary,
List<Equipment>? equipment,
List<ExerciseImage>? images,
List<Translation>? translations,
ExerciseCategory? category,
List<Video>? videos,
List<String>? authors,
List<String>? authorsGlobal,
}) {
this.images = images ?? [];
this.equipment = equipment ?? [];
if (category != null) {
this.category = category;
categoryId = category.id;
}
if (muscles != null) {
this.muscles = muscles;
musclesIds = muscles.map((e) => e.id).toList();
}
if (musclesSecondary != null) {
this.musclesSecondary = musclesSecondary;
musclesSecondaryIds = musclesSecondary.map((e) => e.id).toList();
}
if (equipment != null) {
this.equipment = equipment;
equipmentIds = equipment.map((e) => e.id).toList();
}
if (translations != null) {
this.translations = translations;
}
if (videos != null) {
this.videos = videos;
}
this.authors = authors ?? [];
this.authorsGlobal = authorsGlobal ?? [];
lastUpdateGlobal = DateTime.now();
return Exercise(
id: id ?? this.id,
uuid: uuid ?? this.uuid,
created: created ?? this.created,
lastUpdate: lastUpdate ?? this.lastUpdate,
variationGroup: variationGroup ?? this.variationGroup,
category: category ?? this.category,
muscles: muscles ?? this.muscles,
musclesSecondary: musclesSecondary ?? this.musclesSecondary,
equipment: equipment ?? this.equipment,
images: images ?? this.images,
translations: translations ?? this.translations,
videos: videos ?? this.videos,
authors: authors ?? this.authors,
authorsGlobal: authorsGlobal ?? this.authorsGlobal,
);
}
bool get showPlateCalculator => equipment.map((e) => e.id).contains(ID_EQUIPMENT_BARBELL);
@@ -117,13 +115,13 @@ class Exercise extends Equatable {
final languageCode = language.split('-')[0];
return translations.firstWhere(
(e) => e.languageObj.shortName == languageCode,
(e) => e.language.shortName == languageCode,
orElse: () => translations.firstWhere(
(e) => e.languageObj.shortName == LANGUAGE_SHORT_ENGLISH,
(e) => e.language.shortName == LANGUAGE_SHORT_ENGLISH,
orElse: () {
_logger.info(
'Could not find fallback english translation for exercise-ID $id, returning '
'first language (${translations.first.languageObj.shortName}) instead.',
'first language (${translations.first.language.shortName}) instead.',
);
return translations.first;
},
@@ -135,11 +133,6 @@ class Exercise extends Equatable {
return images.firstWhereOrNull((image) => image.isMain);
}
set setCategory(ExerciseCategory category) {
categoryId = category.id;
this.category = category;
}
@override
List<Object?> get props => [
id,

View File

@@ -16,6 +16,27 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// Art style of an [ExerciseImage].
///
/// The wire values mirror Django's `ExerciseImage.STYLE` choices (`CharField`
/// with `'1'`–`'5'`), so the same string round-trips through PowerSync
/// without any extra mapping on the connector.
enum ExerciseImageStyle {
lineArt('1'),
threeD('2'),
lowPoly('3'),
photo('4'),
other('5')
;
final String wireValue;
const ExerciseImageStyle(this.wireValue);
/// Looks up an enum case by its Django wire value.
static ExerciseImageStyle fromWire(String value) =>
ExerciseImageStyle.values.firstWhere((e) => e.wireValue == value);
}
class ExerciseImage {
final int id;
final String uuid;
@@ -26,6 +47,23 @@ class ExerciseImage {
final String image;
final bool isMain;
final bool isAiGenerated;
final ExerciseImageStyle style;
final int? width;
final int? height;
final DateTime created;
final DateTime lastUpdate;
/// FK to the `License` row.
final int licenseId;
final String licenseTitle;
final String licenseObjectUrl;
/// Author may be null on the server (`TextField(null=True)`).
final String? licenseAuthor;
final String licenseAuthorUrl;
final String licenseDerivativeSourceUrl;
const ExerciseImage({
required this.id,
@@ -33,6 +71,18 @@ class ExerciseImage {
required this.exerciseId,
required this.image,
required this.isMain,
required this.isAiGenerated,
required this.style,
required this.width,
required this.height,
required this.created,
required this.lastUpdate,
required this.licenseId,
required this.licenseTitle,
required this.licenseObjectUrl,
required this.licenseAuthor,
required this.licenseAuthorUrl,
required this.licenseDerivativeSourceUrl,
});
@override

View File

@@ -20,51 +20,33 @@ import 'package:equatable/equatable.dart';
import 'package:wger/models/core/language.dart';
import 'package:wger/models/exercises/alias.dart';
import 'package:wger/models/exercises/comment.dart';
import 'package:wger/models/exercises/exercise.dart';
class Translation extends Equatable {
final int? id;
final String? uuid;
late final int languageId;
late final Language languageObj;
final Language language;
final DateTime? created;
late final int? exerciseId;
final int? exerciseId;
final String name;
final String description;
final String descriptionSource;
final List<Comment> notes;
final List<Alias> aliases;
List<Comment> notes = [];
List<Alias> aliases = [];
int get languageId => language.id;
Translation({
const Translation({
this.id,
this.uuid,
this.created,
required this.name,
required this.description,
this.descriptionSource = '',
int? exerciseId,
Language? language,
}) {
if (exerciseId != null) {
this.exerciseId = exerciseId;
}
if (language != null) {
languageObj = language;
languageId = language.id;
}
}
set exercise(Exercise exercise) {
exerciseId = exercise.id;
}
set language(Language language) {
languageObj = language;
languageId = language.id;
}
this.exerciseId,
required this.language,
this.notes = const [],
this.aliases = const [],
});
@override
List<Object?> get props => [

View File

@@ -19,32 +19,51 @@
class Video {
final int id;
final String uuid;
final int exerciseId;
final bool isMain;
final String url;
Uri get uri => Uri.parse(url);
final int exerciseId;
final int size;
final num duration;
final int width;
final int height;
final String codec;
final String codecLong;
final DateTime created;
final DateTime lastUpdate;
/// FK to the `License` row.
final int licenseId;
final String licenseTitle;
final String licenseObjectUrl;
/// Author may be null on the server (`TextField(null=True)`).
final String? licenseAuthor;
final String licenseAuthorUrl;
final String licenseDerivativeSourceUrl;
const Video({
required this.id,
required this.uuid,
required this.exerciseId,
required this.size,
required this.isMain,
required this.url,
required this.size,
required this.duration,
required this.width,
required this.height,
required this.codec,
required this.codecLong,
required this.created,
required this.lastUpdate,
required this.licenseId,
required this.licenseTitle,
required this.licenseObjectUrl,
required this.licenseAuthor,
required this.licenseAuthorUrl,
required this.licenseDerivativeSourceUrl,
});
}

View File

@@ -14,6 +14,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$MeasurementCategory {
/// Client-generated UUID, is `null` only before the first persist
String? get id; String get name; String get unit; List<MeasurementEntry> get entries;
/// Create a copy of MeasurementCategory
/// with the given fields replaced by the non-null parameter values.

View File

@@ -14,6 +14,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$MeasurementEntry {
/// Client-generated UUID, is `null` only before the first persist
String? get id; String get categoryId; DateTime get date; num get value; String get notes;
/// Create a copy of MeasurementEntry
/// with the given fields replaced by the non-null parameter values.

View File

@@ -40,15 +40,31 @@ class IngredientImage {
@JsonKey(required: true)
final int size;
/// Image width in pixels
@JsonKey(required: true)
final int width;
/// Image height in pixels
@JsonKey(required: true)
final int height;
/// Server creation timestamp
@JsonKey(required: true)
final DateTime created;
/// Server last-modification timestamp
@JsonKey(required: true, name: 'last_update')
final DateTime lastUpdate;
// License information
/// License ID
@JsonKey(required: true, name: 'license')
final int licenseId;
/// Author(s)
/// Author(s) — may be null on the server (`TextField(null=True)`)
@JsonKey(required: true, name: 'license_author')
final String author;
final String? author;
/// Author profile, if available
@JsonKey(required: true, name: 'license_author_url')
@@ -72,6 +88,10 @@ class IngredientImage {
required this.ingredientId,
required this.image,
required this.size,
required this.width,
required this.height,
required this.created,
required this.lastUpdate,
required this.licenseId,
required this.author,
required this.authorUrl,

View File

@@ -15,6 +15,10 @@ IngredientImage _$IngredientImageFromJson(Map<String, dynamic> json) {
'ingredient_id',
'image',
'size',
'width',
'height',
'created',
'last_update',
'license',
'license_author',
'license_author_url',
@@ -29,8 +33,12 @@ IngredientImage _$IngredientImageFromJson(Map<String, dynamic> json) {
ingredientId: (json['ingredient_id'] as num).toInt(),
image: json['image'] as String,
size: (json['size'] as num).toInt(),
width: (json['width'] as num).toInt(),
height: (json['height'] as num).toInt(),
created: DateTime.parse(json['created'] as String),
lastUpdate: DateTime.parse(json['last_update'] as String),
licenseId: (json['license'] as num).toInt(),
author: json['license_author'] as String,
author: json['license_author'] as String?,
authorUrl: json['license_author_url'] as String,
title: json['license_title'] as String,
objectUrl: json['license_object_url'] as String,
@@ -44,6 +52,10 @@ Map<String, dynamic> _$IngredientImageToJson(IngredientImage instance) => <Strin
'ingredient_id': instance.ingredientId,
'image': instance.image,
'size': instance.size,
'width': instance.width,
'height': instance.height,
'created': instance.created.toIso8601String(),
'last_update': instance.lastUpdate.toIso8601String(),
'license': instance.licenseId,
'license_author': instance.author,
'license_author_url': instance.authorUrl,

View File

@@ -28,20 +28,6 @@ import 'package:wger/powersync/api_client.dart';
final logger = Logger('powersync-django');
/// Postgres Response codes that we cannot recover from by retrying.
final List<RegExp> fatalResponseCodes = [
// Class 22 — Data Exception
// Examples include data type mismatch.
RegExp(r'^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
RegExp(r'^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
RegExp(r'^42501$'),
];
/// Exception thrown when the wger backend returned a 200 response whose
/// body indicates that the operation was rejected (validation failure,
/// missing object, ownership violation, unknown table…). Carries the

View File

@@ -27,46 +27,55 @@ import 'package:wger/database/powersync/tables/nutrition.dart';
import 'package:wger/database/powersync/tables/routines.dart';
import 'package:wger/database/powersync/tables/weight.dart';
Schema schema = const Schema([
// Core
PowersyncLanguageTable,
PowersyncLicenseTable,
Schema schema = const Schema(
[
// Core
PowersyncLanguageTable,
PowersyncLicenseTable,
// Exercises
PowersyncExerciseTable,
PowersyncTranslationTable,
PowersyncMuscleTable,
PowersyncExerciseMuscleM2N,
PowersyncExerciseSecondaryMuscleM2N,
PowersyncEquipmentTable,
PowersyncExerciseEquipmentM2N,
PowersyncExerciseCategoryTable,
PowersyncExerciseImageTable,
PowersyncExerciseVideoTable,
// Exercises (large or wide tables live in the rawTables slot below)
PowersyncExerciseAliasTable,
PowersyncExerciseCommentTable,
PowersyncMuscleTable,
PowersyncExerciseMuscleM2N,
PowersyncExerciseSecondaryMuscleM2N,
PowersyncEquipmentTable,
PowersyncExerciseEquipmentM2N,
PowersyncExerciseCategoryTable,
PowersyncExerciseImageTable,
PowersyncExerciseVideoTable,
// Nutrition
PowersyncIngredientTable,
PowersyncIngredientImageTable,
PowersyncIngredientWeightUnitTable,
PowersyncNutritionalPlanTable,
PowersyncMealTable,
PowersyncMealItemTable,
PowersyncLogItemTable,
// Nutrition
PowersyncIngredientTable,
PowersyncIngredientImageTable,
PowersyncIngredientWeightUnitTable,
PowersyncNutritionalPlanTable,
PowersyncMealTable,
PowersyncMealItemTable,
PowersyncLogItemTable,
// Body weight
PowersyncWeightEntryTable,
// Body weight
PowersyncWeightEntryTable,
// Measurements
PowersyncMeasurementCategoryTable,
PowersyncMeasurementEntryTable,
// Measurements
PowersyncMeasurementCategoryTable,
PowersyncMeasurementEntryTable,
// Routines
PowersyncRoutineTable,
PowersyncWorkoutLogTable,
PowersyncWorkoutSessionTable,
PowersyncRoutineRepetitionUnitTable,
PowersyncRoutineWeightUnitTable,
// Routines
PowersyncRoutineTable,
PowersyncWorkoutLogTable,
PowersyncWorkoutSessionTable,
PowersyncRoutineRepetitionUnitTable,
PowersyncRoutineWeightUnitTable,
// Gallery
PowersyncGalleryImageTable,
]);
// Gallery
PowersyncGalleryImageTable,
],
// Raw (native SQLite) tables bypass the JSON-view layer for big read-only
// catalogue tables. The matching CREATE TABLE/INDEX statements live in
// `database/powersync/powersync.dart`.
rawTables: [
PowersyncExerciseTable,
PowersyncTranslationTable,
],
);

View File

@@ -25,7 +25,9 @@ import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/locale.dart';
import 'package:wger/helpers/shared_preferences.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
part 'app_settings_notifier.freezed.dart';
part 'app_settings_notifier.g.dart';
@@ -75,6 +77,9 @@ sealed class AppSettings with _$AppSettings {
const factory AppSettings({
@Default(ThemeMode.system) ThemeMode themeMode,
@Default([]) List<DashboardItem> dashboardItems,
/// Locale override. Null means the app follows the system locale.
Locale? userLocale,
}) = _AppSettings;
}
@@ -91,8 +96,13 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
Future<AppSettings> build() async {
_prefs = ref.read(appSettingsPrefsProvider);
final themeMode = await _loadThemeMode();
final userLocale = await _loadUserLocale();
final items = await _loadDashboardItems();
return AppSettings(themeMode: themeMode, dashboardItems: items);
return AppSettings(
themeMode: themeMode,
userLocale: userLocale,
dashboardItems: items,
);
}
//
@@ -118,6 +128,52 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
}
}
//
// Locale override
//
Future<Locale?> _loadUserLocale() async {
final raw = await _prefs.getString(PREFS_USER_LOCALE);
return _matchSupportedLocale(raw);
}
/// Match a stored locale tag (`languageCode` or `languageCode_subtag`)
/// against [AppLocalizations.supportedLocales]. Returns the exact supported
/// instance to keep dropdown identity stable, or null when no match is found.
static Locale? _matchSupportedLocale(String? raw) {
if (raw == null || raw.isEmpty) {
return null;
}
for (final locale in AppLocalizations.supportedLocales) {
if (encodeLocale(locale) == raw) {
return locale;
}
}
// Fallback: match by language only (e.g. stored "pl" picks the only pl).
final lang = raw.split('_').first;
for (final locale in AppLocalizations.supportedLocales) {
if (locale.languageCode == lang &&
(locale.countryCode == null || locale.countryCode!.isEmpty) &&
(locale.scriptCode == null || locale.scriptCode!.isEmpty)) {
return locale;
}
}
return null;
}
/// Override the app locale. Passing `null` clears the override and falls
/// back to the system locale.
Future<void> setUserLocale(Locale? locale) async {
final current = state.asData?.value ?? const AppSettings();
state = AsyncData(current.copyWith(userLocale: locale));
if (locale == null) {
await _prefs.remove(PREFS_USER_LOCALE);
} else {
await _prefs.setString(PREFS_USER_LOCALE, encodeLocale(locale));
}
}
//
// Dashboard config
//

View File

@@ -14,7 +14,8 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$AppSettings {
ThemeMode get themeMode; List<DashboardItem> get dashboardItems;
ThemeMode get themeMode; List<DashboardItem> get dashboardItems;/// Locale override. Null means the app follows the system locale.
Locale? get userLocale;
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -25,16 +26,16 @@ $AppSettingsCopyWith<AppSettings> get copyWith => _$AppSettingsCopyWithImpl<AppS
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other.dashboardItems, dashboardItems));
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other.dashboardItems, dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale));
}
@override
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems));
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems),userLocale);
@override
String toString() {
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems)';
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale)';
}
@@ -45,7 +46,7 @@ abstract mixin class $AppSettingsCopyWith<$Res> {
factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl;
@useResult
$Res call({
ThemeMode themeMode, List<DashboardItem> dashboardItems
ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale
});
@@ -62,11 +63,12 @@ class _$AppSettingsCopyWithImpl<$Res>
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,}) {
return _then(_self.copyWith(
themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable
as ThemeMode,dashboardItems: null == dashboardItems ? _self.dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable
as List<DashboardItem>,
as List<DashboardItem>,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable
as Locale?,
));
}
@@ -148,10 +150,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _AppSettings() when $default != null:
return $default(_that.themeMode,_that.dashboardItems);case _:
return $default(_that.themeMode,_that.dashboardItems,_that.userLocale);case _:
return orElse();
}
@@ -169,10 +171,10 @@ return $default(_that.themeMode,_that.dashboardItems);case _:
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale) $default,) {final _that = this;
switch (_that) {
case _AppSettings():
return $default(_that.themeMode,_that.dashboardItems);}
return $default(_that.themeMode,_that.dashboardItems,_that.userLocale);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -186,10 +188,10 @@ return $default(_that.themeMode,_that.dashboardItems);}
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( ThemeMode themeMode, List<DashboardItem> dashboardItems)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale)? $default,) {final _that = this;
switch (_that) {
case _AppSettings() when $default != null:
return $default(_that.themeMode,_that.dashboardItems);case _:
return $default(_that.themeMode,_that.dashboardItems,_that.userLocale);case _:
return null;
}
@@ -201,7 +203,7 @@ return $default(_that.themeMode,_that.dashboardItems);case _:
class _AppSettings implements AppSettings {
const _AppSettings({this.themeMode = ThemeMode.system, final List<DashboardItem> dashboardItems = const []}): _dashboardItems = dashboardItems;
const _AppSettings({this.themeMode = ThemeMode.system, final List<DashboardItem> dashboardItems = const [], this.userLocale}): _dashboardItems = dashboardItems;
@override@JsonKey() final ThemeMode themeMode;
@@ -212,6 +214,8 @@ class _AppSettings implements AppSettings {
return EqualUnmodifiableListView(_dashboardItems);
}
/// Locale override. Null means the app follows the system locale.
@override final Locale? userLocale;
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@@ -223,16 +227,16 @@ _$AppSettingsCopyWith<_AppSettings> get copyWith => __$AppSettingsCopyWithImpl<_
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale));
}
@override
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems));
int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems),userLocale);
@override
String toString() {
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems)';
return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale)';
}
@@ -243,7 +247,7 @@ abstract mixin class _$AppSettingsCopyWith<$Res> implements $AppSettingsCopyWith
factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl;
@override @useResult
$Res call({
ThemeMode themeMode, List<DashboardItem> dashboardItems
ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale
});
@@ -260,11 +264,12 @@ class __$AppSettingsCopyWithImpl<$Res>
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,}) {
return _then(_AppSettings(
themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable
as ThemeMode,dashboardItems: null == dashboardItems ? _self._dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable
as List<DashboardItem>,
as List<DashboardItem>,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable
as Locale?,
));
}

View File

@@ -33,7 +33,7 @@ final class AppSettingsNotifierProvider
AppSettingsNotifier create() => AppSettingsNotifier();
}
String _$appSettingsNotifierHash() => r'60f21572cdae5ecba6dfa3f8bb07e76b21812ba3';
String _$appSettingsNotifierHash() => r'43dc14cde2fb06bfda226f18a8ac1196461aa27c';
abstract class _$AppSettingsNotifier extends $AsyncNotifier<AppSettings> {
FutureOr<AppSettings> build();

View File

@@ -121,7 +121,7 @@ class ExerciseListFiltersNotifier extends _$ExerciseListFiltersNotifier {
final term = filters.searchTerm.toLowerCase();
items = items.where((e) {
// TODO: FullTextSearch?
final title = (e.getTranslation(languageCode).name ?? '').toLowerCase();
final title = e.getTranslation(languageCode).name.toLowerCase();
return title.contains(term);
}).toList();
}

View File

@@ -50,7 +50,7 @@ final class ExerciseListFiltersNotifierProvider
}
}
String _$exerciseListFiltersNotifierHash() => r'b6e2571249061a69b53712118615c388f2afefec';
String _$exerciseListFiltersNotifierHash() => r'f2c3c5cee3725dc680c9560743bb50659783860c';
/// Holds the *UI-side* state for the exercises catalogue screen:
/// search term, selected categories/equipment, and the resulting

View File

@@ -16,6 +16,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:drift/drift.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
@@ -23,11 +25,16 @@ import 'package:wger/database/powersync/database.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/models/core/language.dart';
import 'package:wger/models/core/search_options.dart';
import 'package:wger/models/exercises/alias.dart';
import 'package:wger/models/exercises/category.dart';
import 'package:wger/models/exercises/comment.dart';
import 'package:wger/models/exercises/equipment.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/exercise_filters.dart';
import 'package:wger/models/exercises/image.dart';
import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/models/exercises/translation.dart';
import 'package:wger/models/exercises/video.dart';
import 'package:wger/providers/base_provider.dart';
import 'package:wger/providers/exercises_notifier.dart';
import 'package:wger/providers/wger_base.dart';
@@ -127,119 +134,206 @@ class ExerciseRepository {
/// Streams the full exercise catalogue, hydrated with translations,
/// muscles, equipment, category, images and videos.
///
/// Only the exercise + translation (+ translation language) part runs as
/// a SQL JOIN. The reference tables (muscles, equipment, categories) and
/// the fan-out tables (M2N relations, images, videos) are streamed
/// separately and joined in Dart. This is more effective and we don't have to
/// pay drift's per-row mapping for every joined column.
Stream<ExerciseState> watchAllDrift() {
_logger.finer('Watching all local exercises');
final primaryMuscleTable = _db.alias(_db.muscleTable, 'pm');
final secondaryMuscleTable = _db.alias(_db.muscleTable, 'sm');
final joined = _db.select(_db.exerciseTable).join([
// Translations
final exerciseTranslationStream = _db.select(_db.exerciseTable).join([
leftOuterJoin(
_db.exerciseTranslationTable,
_db.exerciseTranslationTable.exerciseId.equalsExp(_db.exerciseTable.id),
),
]).watch();
// Language
leftOuterJoin(
_db.languageTable,
_db.languageTable.id.equalsExp(_db.exerciseTranslationTable.languageId),
),
List<TypedResult>? exerciseRows;
List<Muscle>? muscles;
List<Equipment>? equipment;
List<ExerciseCategory>? categories;
List<Language>? languages;
List<ExerciseMuscleM2NData>? primaryM2N;
List<ExerciseSecondaryMuscleM2NData>? secondaryM2N;
List<ExerciseEquipmentM2NData>? equipmentM2N;
List<ExerciseImage>? images;
List<Video>? videos;
List<Alias>? aliases;
List<Comment>? comments;
// Exercise <-> Muscle
leftOuterJoin(
_db.exerciseMuscleM2N,
_db.exerciseMuscleM2N.exerciseId.equalsExp(_db.exerciseTable.id),
),
leftOuterJoin(
primaryMuscleTable,
primaryMuscleTable.id.equalsExp(_db.exerciseMuscleM2N.muscleId),
),
late StreamController<ExerciseState> controller;
final subs = <StreamSubscription>[];
// Exercise <-> Secondary Muscle
leftOuterJoin(
_db.exerciseSecondaryMuscleM2N,
_db.exerciseSecondaryMuscleM2N.exerciseId.equalsExp(_db.exerciseTable.id),
),
leftOuterJoin(
secondaryMuscleTable,
secondaryMuscleTable.id.equalsExp(_db.exerciseSecondaryMuscleM2N.muscleId),
),
// Exercise <-> Equipment
leftOuterJoin(
_db.exerciseEquipmentM2N,
_db.exerciseEquipmentM2N.exerciseId.equalsExp(_db.exerciseTable.id),
),
leftOuterJoin(
_db.equipmentTable,
_db.equipmentTable.id.equalsExp(_db.exerciseEquipmentM2N.equipmentId),
),
// Category
leftOuterJoin(
_db.exerciseCategoryTable,
_db.exerciseCategoryTable.id.equalsExp(_db.exerciseTable.categoryId),
),
// Images
leftOuterJoin(
_db.exerciseImageTable,
_db.exerciseImageTable.exerciseId.equalsExp(_db.exerciseTable.id),
),
]);
return joined.watch().map((rows) {
final Map<int, Exercise> map = {};
for (final row in rows) {
final exercise = row.readTable(_db.exerciseTable);
final primaryMuscle = row.readTableOrNull(primaryMuscleTable);
final secondaryMuscle = row.readTableOrNull(secondaryMuscleTable);
final equipment = row.readTableOrNull(_db.equipmentTable);
final image = row.readTableOrNull(_db.exerciseImageTable);
final video = row.readTableOrNull(_db.exerciseVideoTable);
final translation = row.readTableOrNull(_db.exerciseTranslationTable);
final category = row.readTableOrNull(_db.exerciseCategoryTable);
final entry = map.putIfAbsent(
exercise.id,
() => exercise,
);
if (category != null) {
entry.category = category;
}
if (translation != null && !entry.translations.any((t) => t.id == translation.id)) {
translation.language = row.readTable(_db.languageTable);
entry.translations.add(translation);
}
if (image != null && !entry.images.any((t) => t.id == image.id)) {
entry.images.add(image);
}
if (video != null && !entry.videos.any((t) => t.id == video.id)) {
entry.videos.add(video);
}
if (equipment != null && !entry.equipment.any((e) => e.id == equipment.id)) {
entry.equipment.add(equipment);
}
if (primaryMuscle != null && !entry.muscles.any((m) => m.id == primaryMuscle.id)) {
entry.muscles.add(primaryMuscle);
}
if (secondaryMuscle != null &&
!entry.musclesSecondary.any((m) => m.id == secondaryMuscle.id)) {
entry.musclesSecondary.add(secondaryMuscle);
}
void emit() {
if (exerciseRows == null ||
muscles == null ||
equipment == null ||
categories == null ||
languages == null ||
primaryM2N == null ||
secondaryM2N == null ||
equipmentM2N == null ||
images == null ||
videos == null ||
aliases == null ||
comments == null) {
return;
}
return ExerciseState(map.values.toList());
});
final muscleById = {for (final m in muscles!) m.id: m};
final equipmentById = {for (final e in equipment!) e.id: e};
final categoryById = {for (final c in categories!) c.id: c};
final languageById = {for (final l in languages!) l.id: l};
final primaryByExercise = <int, List<int>>{};
for (final row in primaryM2N!) {
primaryByExercise.putIfAbsent(row.exerciseId, () => []).add(row.muscleId);
}
final secondaryByExercise = <int, List<int>>{};
for (final row in secondaryM2N!) {
secondaryByExercise.putIfAbsent(row.exerciseId, () => []).add(row.muscleId);
}
final equipmentByExercise = <int, List<int>>{};
for (final row in equipmentM2N!) {
equipmentByExercise.putIfAbsent(row.exerciseId, () => []).add(row.equipmentId);
}
final imagesByExercise = <int, List<ExerciseImage>>{};
for (final img in images!) {
imagesByExercise.putIfAbsent(img.exerciseId, () => []).add(img);
}
final videosByExercise = <int, List<Video>>{};
for (final v in videos!) {
videosByExercise.putIfAbsent(v.exerciseId, () => []).add(v);
}
final aliasesByTranslation = <int, List<Alias>>{};
for (final a in aliases!) {
if (a.translationId != null) {
aliasesByTranslation.putIfAbsent(a.translationId!, () => []).add(a);
}
}
final commentsByTranslation = <int, List<Comment>>{};
for (final c in comments!) {
commentsByTranslation.putIfAbsent(c.translationId, () => []).add(c);
}
// First pass over the exercise+translation JOIN: collect one row per
// exercise (the exercise side repeats per translation) and group the
// hydrated translations by exercise id.
final exerciseRowById = <int, ExerciseRow>{};
final translationsByExercise = <int, List<Translation>>{};
for (final row in exerciseRows!) {
final exerciseRow = row.readTable(_db.exerciseTable);
exerciseRowById[exerciseRow.id] = exerciseRow;
final translationRow = row.readTableOrNull(_db.exerciseTranslationTable);
if (translationRow == null) {
continue;
}
// Skip translations whose language has not synced yet: the language
// table catches up on a later emission, so the translation reappears
// then. This keeps Translation.language a non-null guarantee.
final language = languageById[translationRow.languageId];
if (language == null) {
continue;
}
final list = translationsByExercise.putIfAbsent(exerciseRow.id, () => []);
if (list.any((t) => t.id == translationRow.id)) {
continue;
}
list.add(
Translation(
id: translationRow.id,
uuid: translationRow.uuid,
created: translationRow.created,
name: translationRow.name,
description: translationRow.description,
exerciseId: translationRow.exerciseId,
language: language,
aliases: aliasesByTranslation[translationRow.id] ?? const [],
notes: commentsByTranslation[translationRow.id] ?? const [],
),
);
}
// Second pass: assemble the immutable exercises. Skip any whose
// category has not synced yet (same transient-window argument as the
// translation language above).
final exercises = <Exercise>[];
for (final exerciseRow in exerciseRowById.values) {
final category = categoryById[exerciseRow.categoryId];
if (category == null) {
continue;
}
exercises.add(
Exercise(
id: exerciseRow.id,
uuid: exerciseRow.uuid,
created: exerciseRow.created,
lastUpdate: exerciseRow.lastUpdate,
variationGroup: exerciseRow.variationGroup,
category: category,
muscles: [
for (final id in primaryByExercise[exerciseRow.id] ?? const <int>[])
if (muscleById[id] != null) muscleById[id]!,
],
musclesSecondary: [
for (final id in secondaryByExercise[exerciseRow.id] ?? const <int>[])
if (muscleById[id] != null) muscleById[id]!,
],
equipment: [
for (final id in equipmentByExercise[exerciseRow.id] ?? const <int>[])
if (equipmentById[id] != null) equipmentById[id]!,
],
images: imagesByExercise[exerciseRow.id] ?? const [],
videos: videosByExercise[exerciseRow.id] ?? const [],
translations: translationsByExercise[exerciseRow.id] ?? const [],
),
);
}
controller.add(ExerciseState(exercises));
}
controller = StreamController<ExerciseState>(
onListen: () {
void addSub<T>(Stream<T> source, void Function(T) assign) {
subs.add(
source.listen(
(value) {
assign(value);
emit();
},
onError: controller.addError,
),
);
}
addSub(exerciseTranslationStream, (v) => exerciseRows = v);
addSub(_db.select(_db.muscleTable).watch(), (v) => muscles = v);
addSub(_db.select(_db.equipmentTable).watch(), (v) => equipment = v);
addSub(_db.select(_db.exerciseCategoryTable).watch(), (v) => categories = v);
addSub(_db.select(_db.languageTable).watch(), (v) => languages = v);
addSub(_db.select(_db.exerciseMuscleM2N).watch(), (v) => primaryM2N = v);
addSub(
_db.select(_db.exerciseSecondaryMuscleM2N).watch(),
(v) => secondaryM2N = v,
);
addSub(_db.select(_db.exerciseEquipmentM2N).watch(), (v) => equipmentM2N = v);
addSub(_db.select(_db.exerciseImageTable).watch(), (v) => images = v);
addSub(_db.select(_db.exerciseVideoTable).watch(), (v) => videos = v);
addSub(_db.select(_db.exerciseAliasTable).watch(), (v) => aliases = v);
addSub(_db.select(_db.exerciseCommentTable).watch(), (v) => comments = v);
},
onCancel: () async {
for (final s in subs) {
await s.cancel();
}
},
);
return controller.stream;
}
/// Streams all exercise categories.

View File

@@ -23,6 +23,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:logging/logging.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/database/powersync/database.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/models/gallery/image.dart';
@@ -67,9 +68,11 @@ class GalleryRepository {
..fields['date'] = dateToYYYYMMDD(image.date)!
..fields['description'] = image.description;
final res = await request.send();
final respStr = await res.stream.bytesToString();
return GalleryImage.fromJson(json.decode(respStr) as Map<String, dynamic>);
final response = await http.Response.fromStream(await request.send());
if (response.statusCode >= 400) {
throw WgerHttpException(response);
}
return GalleryImage.fromJson(json.decode(response.body) as Map<String, dynamic>);
}
/// PATCHes an image whose binary file has changed. Returns the new
@@ -82,9 +85,11 @@ class GalleryRepository {
..fields['date'] = dateToYYYYMMDD(image.date)!
..fields['description'] = image.description;
final res = await request.send();
final respStr = await res.stream.bytesToString();
final responseData = json.decode(respStr);
final response = await http.Response.fromStream(await request.send());
if (response.statusCode >= 400) {
throw WgerHttpException(response);
}
final responseData = json.decode(response.body);
return responseData['image'] as String?;
}

View File

@@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider<GymStateNotifier,
}
}
String _$gymStateNotifierHash() => r'2d23db0ad9da2b0266a81048c02d9c8241f267dc';
String _$gymStateNotifierHash() => r'213315cfc2f3047fe99ab88e81ee7e570e7c6ec3';
abstract class _$GymStateNotifier extends $Notifier<GymModeState> {
GymModeState build();

View File

@@ -27,22 +27,18 @@ import 'package:wger/models/nutrition/log.dart';
import 'package:wger/models/nutrition/meal.dart';
import 'package:wger/models/nutrition/meal_item.dart';
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/providers/base_provider.dart';
import 'package:wger/providers/wger_base.dart';
final nutritionRepositoryProvider = Provider<NutritionRepository>((ref) {
final base = ref.read(wgerBaseProvider);
final db = ref.read(driftPowerSyncDatabase);
return NutritionRepository(base, db);
return NutritionRepository(db);
});
/// Data access for nutrition-related entities.
class NutritionRepository {
final _logger = Logger('NutritionRepository');
final WgerBaseProvider _base;
final DriftPowersyncDatabase _db;
NutritionRepository(this._base, this._db);
NutritionRepository(this._db);
// --- Plans ---

View File

@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:wger/models/workouts/session.dart';
import 'package:wger/providers/workout_session_repository.dart';
@@ -25,7 +24,6 @@ part 'workout_session_notifier.g.dart';
@Riverpod(keepAlive: true)
final class WorkoutSessionNotifier extends _$WorkoutSessionNotifier {
final _logger = Logger('WorkoutSessionNotifier');
late WorkoutSessionRepository _repo;
@override

View File

@@ -33,7 +33,7 @@ final class WorkoutSessionNotifierProvider
WorkoutSessionNotifier create() => WorkoutSessionNotifier();
}
String _$workoutSessionNotifierHash() => r'4ca757bd63400433d86d3d597ee6cf1718246dcb';
String _$workoutSessionNotifierHash() => r'82394a22af6348c7a228d757b7757a8d394e91a4';
abstract class _$WorkoutSessionNotifier extends $StreamNotifier<List<WorkoutSession>> {
Stream<List<WorkoutSession>> build();

View File

@@ -18,11 +18,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/nutrition/meal.dart';
import 'package:wger/providers/nutrition_notifier.dart';
import 'package:wger/widgets/core/datetime_input.dart';
import 'package:wger/widgets/nutrition/meal.dart';
import 'package:wger/widgets/nutrition/nutrition_tiles.dart';
@@ -44,27 +43,11 @@ class LogMealScreen extends ConsumerStatefulWidget {
class _LogMealScreenState extends ConsumerState<LogMealScreen> {
double portionPct = 100;
final _dateController = TextEditingController(text: '');
final _timeController = TextEditingController();
@override
void initState() {
super.initState();
_timeController.text = timeToString(TimeOfDay.now())!;
}
@override
void dispose() {
_dateController.dispose();
_timeController.dispose();
super.dispose();
}
DateTime _date = DateTime.now();
TimeOfDay _time = TimeOfDay.now();
@override
Widget build(BuildContext context) {
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
final dateTimeFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode).add_Hm();
final i18n = AppLocalizations.of(context);
final args = ModalRoute.of(context)!.settings.arguments as LogMealArguments;
@@ -74,10 +57,6 @@ class _LogMealScreenState extends ConsumerState<LogMealScreen> {
.toList(),
);
if (_dateController.text.isEmpty) {
_dateController.text = dateFormat.format(DateTime.now());
}
return Scaffold(
appBar: AppBar(title: Text(i18n.logMeal)),
body: Consumer(
@@ -120,50 +99,22 @@ class _LogMealScreenState extends ConsumerState<LogMealScreen> {
children: [
const Padding(padding: EdgeInsets.symmetric(horizontal: 12)),
Expanded(
child: TextFormField(
child: DateInputWidget(
key: const ValueKey('field-date'),
readOnly: true,
decoration: InputDecoration(labelText: i18n.date),
enableInteractiveSelection: false,
controller: _dateController,
onTap: () async {
final pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now().subtract(const Duration(days: 3000)),
lastDate: DateTime.now(),
);
if (pickedDate != null) {
_dateController.text = dateFormat.format(pickedDate);
}
},
onSaved: (newValue) {
_dateController.text = newValue!;
},
value: _date,
labelText: i18n.date,
firstDate: DateTime.now().subtract(const Duration(days: 3000)),
lastDate: DateTime.now(),
onChanged: (date) => _date = date,
),
),
const Padding(padding: EdgeInsets.symmetric(horizontal: 12)),
Expanded(
child: TextFormField(
child: TimeInputWidget(
key: const ValueKey('field-time'),
readOnly: true,
decoration: InputDecoration(labelText: i18n.time),
controller: _timeController,
onTap: () async {
// Open time picker
final pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(DateTime.now()),
);
if (pickedTime != null) {
_timeController.text = timeToString(pickedTime)!;
}
},
onSaved: (newValue) {
_timeController.text = newValue!;
},
value: _time,
labelText: i18n.time,
onChanged: (time) => _time = time,
),
),
const Padding(padding: EdgeInsets.symmetric(horizontal: 12)),
@@ -177,8 +128,12 @@ class _LogMealScreenState extends ConsumerState<LogMealScreen> {
TextButton(
child: Text(i18n.save),
onPressed: () async {
final loggedDate = dateTimeFormat.parse(
'${_dateController.text} ${_timeController.text}',
final loggedDate = DateTime(
_date.year,
_date.month,
_date.day,
_time.hour,
_time.minute,
);
await ref
.read(nutritionProvider.notifier)

View File

@@ -21,7 +21,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg_icons/flutter_svg_icons.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/nutrition_notifier.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/screens/log_meals_screen.dart';
@@ -55,7 +54,6 @@ class _NutritionalPlanScreenState extends ConsumerState<NutritionalPlanScreen> {
@override
Widget build(BuildContext context) {
const appBarForeground = Colors.white;
final isOnline = ref.watch(networkStatusProvider);
// Resolve the freshest plan from state so meal/diary edits reflect
// immediately. Falls back to the route argument if state hasn't streamed
// yet (e.g. cold open, deep link).
@@ -70,20 +68,17 @@ class _NutritionalPlanScreenState extends ConsumerState<NutritionalPlanScreen> {
FloatingActionButton(
heroTag: null,
tooltip: AppLocalizations.of(context).logIngredient,
backgroundColor: isOnline ? null : Colors.grey,
onPressed: isOnline
? () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).logIngredient,
getIngredientLogForm(_nutritionalPlan),
hasListView: true,
),
);
}
: null,
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).logIngredient,
getIngredientLogForm(_nutritionalPlan),
hasListView: true,
),
);
},
child: const SvgIcon(
icon: SvgIconData('assets/icons/ingredient-diary.svg'),
color: Colors.white,
@@ -93,15 +88,12 @@ class _NutritionalPlanScreenState extends ConsumerState<NutritionalPlanScreen> {
FloatingActionButton(
heroTag: null,
tooltip: AppLocalizations.of(context).logMeal,
backgroundColor: isOnline ? null : Colors.grey,
onPressed: isOnline
? () {
Navigator.of(context).pushNamed(
LogMealsScreen.routeName,
arguments: _nutritionalPlan,
);
}
: null,
onPressed: () {
Navigator.of(context).pushNamed(
LogMealsScreen.routeName,
arguments: _nutritionalPlan,
);
},
child: const SvgIcon(
icon: SvgIconData('assets/icons/meal-diary.svg'),
color: Colors.white,
@@ -121,18 +113,16 @@ class _NutritionalPlanScreenState extends ConsumerState<NutritionalPlanScreen> {
icon: const SvgIcon(
icon: SvgIconData('assets/icons/meal-add.svg'),
),
onPressed: isOnline
? () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).addMeal,
MealForm(_nutritionalPlan.id!),
),
);
}
: null,
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).addMeal,
MealForm(_nutritionalPlan.id!),
),
);
},
),
PopupMenuButton<NutritionalPlanOptions>(
icon: const Icon(Icons.more_vert, color: appBarForeground),
@@ -159,7 +149,6 @@ class _NutritionalPlanScreenState extends ConsumerState<NutritionalPlanScreen> {
return [
PopupMenuItem<NutritionalPlanOptions>(
value: NutritionalPlanOptions.edit,
enabled: isOnline,
child: ListTile(
leading: const Icon(Icons.edit),
title: Text(AppLocalizations.of(context).edit),
@@ -168,7 +157,6 @@ class _NutritionalPlanScreenState extends ConsumerState<NutritionalPlanScreen> {
const PopupMenuDivider(),
PopupMenuItem<NutritionalPlanOptions>(
value: NutritionalPlanOptions.delete,
enabled: isOnline,
child: ListTile(
leading: const Icon(Icons.delete),
title: Text(AppLocalizations.of(context).delete),

View File

@@ -20,7 +20,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/wide_screen_wrapper.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/screens/ingredients_screen.dart';
import 'package:wger/widgets/nutrition/forms.dart';
@@ -37,8 +36,6 @@ class NutritionalPlansScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final isOnline = ref.watch(networkStatusProvider);
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).nutritionalPlans),
@@ -63,20 +60,17 @@ class NutritionalPlansScreen extends ConsumerWidget {
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: isOnline ? null : Colors.grey,
onPressed: isOnline
? () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newNutritionalPlan,
hasListView: true,
PlanForm(),
),
);
}
: null,
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).newNutritionalPlan,
hasListView: true,
PlanForm(),
),
);
},
child: const Icon(Icons.add, color: Colors.white),
),
body: const WidescreenWrapper(child: NutritionalPlansList()),

View File

@@ -0,0 +1,232 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
/// Read-only field that opens a time picker on tap.
///
/// The selected time is reported through [onChanged]; the caller keeps the
/// source of truth and decides how to store it. The displayed text uses the
/// active locale's time format (12h with AM/PM where the device prefers it),
/// so it must never be parsed back into a [TimeOfDay].
///
/// When [onCleared] is provided, a clear button is shown while a value is set.
class TimeInputWidget extends StatefulWidget {
const TimeInputWidget({
required this.value,
required this.onChanged,
required this.labelText,
this.onCleared,
this.validator,
super.key,
});
/// The currently selected time, or null when unset.
final TimeOfDay? value;
/// Called with the time picked from the dialog.
final ValueChanged<TimeOfDay> onChanged;
final String labelText;
/// When provided, a clear button is shown while [value] is set; tapping it
/// invokes this callback.
final VoidCallback? onCleared;
/// Optional form validator. The argument is the displayed text; cross-field
/// rules should read the source of truth from the surrounding state instead.
final FormFieldValidator<String>? validator;
@override
State<TimeInputWidget> createState() => _TimeInputWidgetState();
}
class _TimeInputWidgetState extends State<TimeInputWidget> {
final _controller = TextEditingController();
TimeOfDay? _value;
@override
void initState() {
super.initState();
_value = widget.value;
}
@override
void didUpdateWidget(TimeInputWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.value != oldWidget.value) {
_value = widget.value;
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// The field is read-only, so rewriting the display text every build is safe.
_controller.text = _value?.format(context) ?? '';
return TextFormField(
readOnly: true,
controller: _controller,
validator: widget.validator,
decoration: InputDecoration(
labelText: widget.labelText,
errorMaxLines: 2,
suffixIcon: widget.onCleared != null && _value != null
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() => _value = null);
widget.onCleared!();
},
)
: const Icon(Icons.access_time_outlined),
),
onTap: () async {
// Stop the keyboard from appearing for the read-only field.
FocusScope.of(context).requestFocus(FocusNode());
final picked = await showTimePicker(
context: context,
initialTime: _value ?? TimeOfDay.now(),
);
if (picked != null && context.mounted) {
setState(() => _value = picked);
widget.onChanged(picked);
}
},
);
}
}
/// Read-only field that opens a date picker on tap.
///
/// The selected date is reported through [onChanged]; the caller keeps the
/// source of truth and decides how to store it. The displayed text uses the
/// active locale's date format.
///
/// When [onCleared] is provided, a clear button is shown while a value is set.
class DateInputWidget extends StatefulWidget {
const DateInputWidget({
required this.value,
required this.onChanged,
required this.labelText,
this.firstDate,
this.lastDate,
this.onCleared,
this.validator,
super.key,
});
/// The currently selected date, or null when unset.
final DateTime? value;
/// Called with the date picked from the dialog.
final ValueChanged<DateTime> onChanged;
final String labelText;
/// Earliest selectable date. Defaults to the year 2000.
final DateTime? firstDate;
/// Latest selectable date. Defaults to the year 2100.
final DateTime? lastDate;
/// When provided, a clear button is shown while [value] is set; tapping it
/// invokes this callback.
final VoidCallback? onCleared;
/// Optional form validator. The argument is the displayed text; cross-field
/// rules should read the source of truth from the surrounding state instead.
final FormFieldValidator<String>? validator;
@override
State<DateInputWidget> createState() => _DateInputWidgetState();
}
class _DateInputWidgetState extends State<DateInputWidget> {
final _controller = TextEditingController();
DateTime? _value;
@override
void initState() {
super.initState();
_value = widget.value;
}
@override
void didUpdateWidget(DateInputWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.value != oldWidget.value) {
_value = widget.value;
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
// The field is read-only, so rewriting the display text every build is safe.
_controller.text = _value != null ? dateFormat.format(_value!) : '';
return TextFormField(
readOnly: true,
controller: _controller,
validator: widget.validator,
decoration: InputDecoration(
labelText: widget.labelText,
errorMaxLines: 2,
suffixIcon: widget.onCleared != null && _value != null
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() => _value = null);
widget.onCleared!();
},
)
: const Icon(Icons.calendar_today),
),
onTap: () async {
// Stop the keyboard from appearing for the read-only field.
FocusScope.of(context).requestFocus(FocusNode());
final picked = await showDatePicker(
context: context,
initialDate: _value ?? DateTime.now(),
firstDate: widget.firstDate ?? DateTime(2000),
lastDate: widget.lastDate ?? DateTime(2100),
);
if (picked != null && context.mounted) {
setState(() => _value = picked);
widget.onChanged(picked);
}
},
);
}
}

View File

@@ -0,0 +1,79 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
/// Locale-aware decimal text field.
///
/// Renders [value] with the active locale's number format and reports edits
/// through [onChanged] as a parsed [num], or null when the field is empty.
/// Display and parsing always go through the same NumberFormat, so a value can
/// never be mis-read because of a decimal-separator mismatch between locales.
class DecimalInputWidget extends StatelessWidget {
const DecimalInputWidget({
required this.value,
required this.onChanged,
required this.labelText,
this.suffixText,
this.isRequired = false,
super.key,
});
/// The current value, or null when unset.
final num? value;
/// Called with the parsed value on every edit, or null when the field is
/// cleared or its contents cannot be parsed.
final ValueChanged<num?> onChanged;
final String labelText;
final String? suffixText;
/// When true, an empty field fails validation instead of being accepted.
final bool isRequired;
@override
Widget build(BuildContext context) {
final i18n = AppLocalizations.of(context);
final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString());
return TextFormField(
initialValue: value == null ? '' : numberFormat.format(value),
decoration: InputDecoration(labelText: labelText, suffixText: suffixText),
keyboardType: textInputTypeDecimal,
onChanged: (text) {
final trimmed = text.trim();
onChanged(trimmed.isEmpty ? null : numberFormat.tryParse(trimmed));
},
validator: (text) {
final trimmed = text?.trim() ?? '';
if (trimmed.isEmpty) {
return isRequired ? i18n.enterValue : null;
}
if (numberFormat.tryParse(trimmed) == null) {
return i18n.enterValidNumber;
}
return null;
},
);
}
}

View File

@@ -0,0 +1,89 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/helpers/errors.dart';
import 'package:wger/widgets/core/progress_indicator.dart';
/// Submit button that owns the saving and error state of an async form action.
///
/// While [onPressed] is in flight the button is disabled and renders a
/// [FormProgressIndicator], which also prevents a double submit. A
/// [WgerHttpException] thrown by [onPressed] is caught and rendered as a
/// [FormHttpErrorsWidget] directly above the button, other errors propagate
/// to the global error handler. Set [enabled] to false to disable the button
/// for other reasons, e.g. while offline.
class FormSubmitButton extends StatefulWidget {
const FormSubmitButton({
required this.onPressed,
required this.label,
this.enabled = true,
super.key,
});
/// Async submit action. The spinner is shown until the returned future
/// completes. A [WgerHttpException] is rendered inline; any other error is
/// left to propagate.
final Future<void> Function() onPressed;
final String label;
/// When false the button is disabled regardless of the saving state.
final bool enabled;
@override
State<FormSubmitButton> createState() => _FormSubmitButtonState();
}
class _FormSubmitButtonState extends State<FormSubmitButton> {
bool _isSaving = false;
WgerHttpException? _error;
Future<void> _handlePressed() async {
setState(() {
_isSaving = true;
_error = null;
});
try {
await widget.onPressed();
} on WgerHttpException catch (error) {
if (mounted) {
setState(() => _error = error);
}
} finally {
if (mounted) {
setState(() => _isSaving = false);
}
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_error != null) FormHttpErrorsWidget(_error!),
ElevatedButton(
onPressed: _isSaving || !widget.enabled ? null : _handlePressed,
child: _isSaving ? const FormProgressIndicator() : Text(widget.label),
),
],
);
}
}

View File

@@ -21,6 +21,7 @@ import 'package:wger/core/wide_screen_wrapper.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/screens/settings_plates_screen.dart';
import 'package:wger/widgets/core/settings/image_cache.dart';
import 'package:wger/widgets/core/settings/language.dart';
import 'package:wger/widgets/core/settings/theme.dart';
class SettingsPage extends StatelessWidget {
@@ -46,6 +47,7 @@ class SettingsPage extends StatelessWidget {
const SettingsImageCache(),
ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)),
const SettingsTheme(),
const SettingsLanguage(),
ListTile(
title: Text(i18n.selectAvailablePlates),
onTap: () {

View File

@@ -0,0 +1,68 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/helpers/locale.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/l10n/language_native_names.dart';
import 'package:wger/providers/app_settings_notifier.dart';
String _displayNameFor(Locale locale) {
return languageNativeNames[encodeLocale(locale)] ??
languageNativeNames[locale.languageCode] ??
encodeLocale(locale);
}
class SettingsLanguage extends ConsumerWidget {
const SettingsLanguage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final i18n = AppLocalizations.of(context);
final userLocale = ref.watch(
appSettingsProvider.select((s) => s.value?.userLocale),
);
final supported = [...AppLocalizations.supportedLocales]
..sort((a, b) => _displayNameFor(a).compareTo(_displayNameFor(b)));
return ListTile(
title: Text(i18n.appLanguage),
trailing: DropdownButton<Locale?>(
key: const ValueKey('appLanguageDropdown'),
value: userLocale,
onChanged: (Locale? newValue) {
ref.read(appSettingsProvider.notifier).setUserLocale(newValue);
},
items: <DropdownMenuItem<Locale?>>[
DropdownMenuItem<Locale?>(
value: null,
child: Text(i18n.appLanguageSystem),
),
...supported.map(
(locale) => DropdownMenuItem<Locale?>(
value: locale,
child: Text(_displayNameFor(locale)),
),
),
],
),
);
}
}

View File

@@ -22,6 +22,8 @@ import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/trophies/trophy.dart';
import 'package:wger/providers/trophy_notifier.dart';
import 'package:wger/screens/trophy_screen.dart';
import 'package:wger/widgets/core/core.dart';
import 'package:wger/widgets/core/wger_image.dart';
class DashboardTrophiesWidget extends ConsumerWidget {
const DashboardTrophiesWidget();
@@ -105,9 +107,16 @@ class TrophyCard extends StatelessWidget {
children: [
Row(
children: [
CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(trophy.image),
WgerImage(
mediaPath: trophy.image,
width: 60,
height: 60,
cacheWidth: 180,
borderRadius: BorderRadius.circular(30),
errorWidget: const CircleIconAvatar(
Icon(Icons.emoji_events, color: Colors.grey),
radius: 30,
),
),
const SizedBox(width: 10),
Expanded(

View File

@@ -106,7 +106,7 @@ class _ExerciseAutocompleterState extends ConsumerState<ExerciseAutocompleter> {
exercise.getTranslation(languageCode).name,
),
subtitle: Text(
'${exercise.category!.name} / ${exercise.equipment.map((e) => e.name).join(', ')}',
'${exercise.category.name} / ${exercise.equipment.map((e) => e.name).join(', ')}',
),
),
emptyBuilder: (context) {

View File

@@ -34,7 +34,7 @@ class CategoryEquipmentRow extends StatelessWidget {
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Chip(
label: Text(getServerStringTranslation(exercise.category!.name, context)),
label: Text(getServerStringTranslation(exercise.category.name, context)),
padding: EdgeInsets.zero,
backgroundColor: theme.splashColor,
),

View File

@@ -52,7 +52,7 @@ class ExerciseListTile extends StatelessWidget {
maxLines: 2,
),
subtitle: Text(
'${getServerStringTranslation(exercise.category!.name, context)} / ${exercise.equipment.map((e) => getServerStringTranslation(e.name, context)).toList().join(', ')}',
'${getServerStringTranslation(exercise.category.name, context)} / ${exercise.equipment.map((e) => getServerStringTranslation(e.name, context)).toList().join(', ')}',
),
onTap: () {
Navigator.pushNamed(context, ExerciseDetailScreen.routeName, arguments: exercise);

View File

@@ -27,6 +27,7 @@ import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/gallery/image.dart';
import 'package:wger/providers/gallery_notifier.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/widgets/core/form_submit_button.dart';
import 'package:wger/widgets/core/wger_image.dart';
class ImageForm extends ConsumerStatefulWidget {
@@ -103,6 +104,10 @@ class _ImageFormState extends ConsumerState<ImageForm> {
Widget build(BuildContext context) {
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
final isOnline = ref.watch(networkStatusProvider);
// Creating an image or replacing its photo is a binary REST upload and
// needs connectivity. A metadata-only edit syncs through PowerSync and
// works offline.
final requiresUpload = widget._image.id == null || _file != null;
if (dateController.text.isEmpty) {
dateController.text = dateFormat.format(widget._image.date);
@@ -197,27 +202,28 @@ class _ImageFormState extends ConsumerState<ImageForm> {
widget._image.description = newValue!;
},
),
ElevatedButton(
FormSubmitButton(
key: const Key(SUBMIT_BUTTON_KEY_NAME),
child: Text(AppLocalizations.of(context).save),
onPressed: isOnline
? () async {
// Validate and save
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
enabled: !(requiresUpload && !isOnline),
label: AppLocalizations.of(context).save,
onPressed: () async {
// Validate and save
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
final notifier = ref.read(galleryProvider.notifier);
if (widget._image.id == null) {
notifier.addImage(widget._image, _file!);
} else {
notifier.editImage(widget._image, _file);
}
Navigator.of(context).pop();
}
: null,
final notifier = ref.read(galleryProvider.notifier);
if (widget._image.id == null) {
await notifier.addImage(widget._image, _file!);
} else {
await notifier.editImage(widget._image, _file);
}
if (context.mounted) {
Navigator.of(context).pop();
}
},
),
],
),

View File

@@ -24,7 +24,6 @@ import 'package:wger/helpers/platform.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/gallery/image.dart';
import 'package:wger/providers/gallery_notifier.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/widgets/core/text_prompt.dart';
import 'package:wger/widgets/core/wger_image.dart';
@@ -79,7 +78,6 @@ class ImageDetail extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final isOnline = ref.watch(networkStatusProvider);
return Container(
key: Key('image-${image.id!}-detail'),
padding: const EdgeInsets.all(10),
@@ -104,29 +102,25 @@ class ImageDetail extends ConsumerWidget {
children: [
IconButton(
icon: const Icon(Icons.delete),
onPressed: isOnline
? () {
ref.read(galleryProvider.notifier).deleteImage(image);
Navigator.of(context).pop();
}
: null,
onPressed: () {
ref.read(galleryProvider.notifier).deleteImage(image);
Navigator.of(context).pop();
},
),
if (!isDesktop)
IconButton(
icon: const Icon(Icons.edit),
onPressed: isOnline
? () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).edit,
ImageForm(image),
hasListView: true,
),
);
}
: null,
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).edit,
ImageForm(image),
hasListView: true,
),
);
},
),
],
),

View File

@@ -18,12 +18,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/measurements/measurement_category.dart';
import 'package:wger/models/measurements/measurement_entry.dart';
import 'package:wger/providers/measurement_notifier.dart';
import 'package:wger/widgets/core/datetime_input.dart';
import 'package:wger/widgets/core/decimal_input.dart';
import 'package:wger/widgets/core/error.dart';
import 'package:wger/widgets/core/progress_indicator.dart';
@@ -111,8 +111,7 @@ class MeasurementEntryForm extends ConsumerStatefulWidget {
final String _categoryId;
final MeasurementEntry? _entry;
const MeasurementEntryForm(this._categoryId, [MeasurementEntry? entry])
: _entry = entry;
const MeasurementEntryForm(this._categoryId, [MeasurementEntry? entry]) : _entry = entry;
@override
ConsumerState<MeasurementEntryForm> createState() => _MeasurementEntryFormState();
@@ -120,9 +119,6 @@ class MeasurementEntryForm extends ConsumerStatefulWidget {
class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
final _form = GlobalKey<FormState>();
final _valueController = TextEditingController();
final _dateController = TextEditingController();
final _timeController = TextEditingController();
final _notesController = TextEditingController();
late final String? _existingId = widget._entry?.id;
@@ -140,37 +136,17 @@ class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
@override
void dispose() {
_valueController.dispose();
_dateController.dispose();
_timeController.dispose();
_notesController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
final timeFormat = DateFormat.Hm(Localizations.localeOf(context).languageCode);
final notifier = ref.read(measurementProvider.notifier);
final Future<MeasurementCategory?> categoryFuture = notifier.getCategoryById(
widget._categoryId,
);
if (_dateController.text.isEmpty) {
_dateController.text = dateFormat.format(_date);
}
if (_timeController.text.isEmpty) {
_timeController.text = timeFormat.format(_date);
}
final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString());
// If the value is not empty, format it
if (_valueController.text.isEmpty && _value != null) {
_valueController.text = numberFormat.format(_value);
}
return FutureBuilder(
future: categoryFuture,
builder: (context, snapshot) {
@@ -191,104 +167,40 @@ class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
child: Column(
children: [
// Date
TextFormField(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).date,
suffixIcon: const Icon(
Icons.calendar_today,
key: Key('calendarIcon'),
),
),
readOnly: true,
controller: _dateController,
onTap: () async {
FocusScope.of(context).requestFocus(FocusNode());
final pickedDate = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime(DateTime.now().year - 10),
lastDate: DateTime.now(),
DateInputWidget(
value: _date,
labelText: AppLocalizations.of(context).date,
firstDate: DateTime(DateTime.now().year - 10),
lastDate: DateTime.now(),
onChanged: (date) {
_date = _date.copyWith(
year: date.year,
month: date.month,
day: date.day,
);
if (pickedDate != null) {
_dateController.text = dateFormat.format(pickedDate);
}
},
onSaved: (newValue) {
final date = dateFormat.parse(newValue!);
_date = _date.copyWith(year: date.year, month: date.month, day: date.day);
},
validator: (value) {
if (value!.isEmpty) {
return AppLocalizations.of(context).enterValue;
}
return null;
},
),
// Time
TextFormField(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).time,
suffixIcon: const Icon(
Icons.access_time_outlined,
key: Key('clockIcon'),
),
),
readOnly: true,
controller: _timeController,
onTap: () async {
final pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(_date),
);
if (pickedTime != null) {
final now = DateTime.now();
final dt = DateTime(
now.year,
now.month,
now.day,
pickedTime.hour,
pickedTime.minute,
);
_timeController.text = timeFormat.format(dt);
}
},
onSaved: (newValue) {
final time = timeFormat.parse(newValue!);
TimeInputWidget(
value: TimeOfDay.fromDateTime(_date),
labelText: AppLocalizations.of(context).time,
onChanged: (time) {
_date = _date.copyWith(
hour: time.hour,
minute: time.minute,
second: time.second,
second: 0,
);
},
),
// Value
TextFormField(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).value,
suffixIcon: Text(category.unit),
suffixIconConstraints: const BoxConstraints(minWidth: 0, minHeight: 0),
),
controller: _valueController,
keyboardType: textInputTypeDecimal,
validator: (value) {
if (value!.isEmpty) {
return AppLocalizations.of(context).enterValue;
}
try {
numberFormat.parse(value);
} catch (error) {
return AppLocalizations.of(context).enterValidNumber;
}
return null;
},
onSaved: (newValue) {
_value = numberFormat.parse(newValue!);
},
DecimalInputWidget(
value: _value,
labelText: AppLocalizations.of(context).value,
suffixText: category.unit,
isRequired: true,
onChanged: (value) => _value = value,
),
// Notes
TextFormField(

View File

@@ -20,7 +20,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/ingredient_weight_unit.dart';
@@ -30,6 +29,8 @@ import 'package:wger/models/nutrition/meal_item.dart';
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/providers/nutrition_notifier.dart';
import 'package:wger/screens/nutritional_plan_screen.dart';
import 'package:wger/widgets/core/datetime_input.dart';
import 'package:wger/widgets/core/decimal_input.dart';
import 'package:wger/widgets/nutrition/helpers.dart';
import 'package:wger/widgets/nutrition/nutrition_tiles.dart';
import 'package:wger/widgets/nutrition/widgets.dart';
@@ -39,44 +40,28 @@ class MealForm extends ConsumerWidget {
final String _planId;
final _form = GlobalKey<FormState>();
final _timeController = TextEditingController();
final _nameController = TextEditingController();
MealForm(this._planId, [meal]) {
_meal = meal ?? Meal(plan: _planId, time: TimeOfDay.fromDateTime(DateTime.now()));
_timeController.text = timeToString(_meal.time)!;
_nameController.text = _meal.name;
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final isCreating = _meal.id == null;
return Container(
margin: const EdgeInsets.all(20),
child: Form(
key: _form,
child: Column(
children: [
TextFormField(
TimeInputWidget(
key: const Key('field-time'),
decoration: InputDecoration(labelText: AppLocalizations.of(context).time),
controller: _timeController,
onTap: () async {
// Stop keyboard from appearing
FocusScope.of(context).requestFocus(FocusNode());
// Open time picker
final pickedTime = await showTimePicker(
context: context,
initialTime: _meal.time!,
);
if (pickedTime != null) {
_timeController.text = timeToString(pickedTime)!;
}
},
onSaved: (newValue) {
_meal.time = stringToTimeNull(newValue);
},
value: _meal.time,
labelText: AppLocalizations.of(context).time,
onChanged: (time) => _meal.time = time,
),
TextFormField(
maxLength: 25,
@@ -173,8 +158,8 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
final _ingredientController = TextEditingController();
final _ingredientIdController = TextEditingController();
final _amountController = TextEditingController();
final _dateController = TextEditingController(); // optional
final _timeController = TextEditingController(text: ''); // optional
DateTime _date = DateTime.now();
TimeOfDay _time = TimeOfDay.now();
final _mealItem = MealItem.empty();
var _searchQuery = ''; // copy from typeahead. for filtering suggestions
List<IngredientWeightUnit> _weightUnits = [];
@@ -185,8 +170,6 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
_ingredientController.dispose();
_ingredientIdController.dispose();
_amountController.dispose();
_dateController.dispose();
_timeController.dispose();
super.dispose();
}
@@ -227,20 +210,8 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
@override
Widget build(BuildContext context) {
final languageCode = Localizations.localeOf(context).languageCode;
final dateFormat = DateFormat.yMd(languageCode);
final timeFormat = DateFormat.Hm(languageCode);
final dateTimeFormat = DateFormat.yMd(languageCode).add_Hm();
final i18n = AppLocalizations.of(context);
if (_dateController.text.isEmpty) {
_dateController.text = dateFormat.format(DateTime.now());
}
if (_timeController.text.isEmpty) {
_timeController.text = timeFormat.format(DateTime.now());
}
final String unit = i18n.g;
final queryLower = _searchQuery.toLowerCase();
final suggestions = widget.recent
@@ -309,7 +280,7 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
keyboardType: textInputTypeDecimal,
onChanged: (value) {
setState(() {
final v = double.tryParse(value);
final v = numberFormat.tryParse(value);
if (v != null) {
_mealItem.amount = v;
}
@@ -323,7 +294,7 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
if (text.isEmpty) {
return i18n.enterValue;
}
final parsed = double.tryParse(text);
final parsed = numberFormat.tryParse(text);
if (parsed == null) {
return i18n.enterValidNumber;
}
@@ -337,58 +308,21 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
),
if (widget.withDate)
Expanded(
child: TextFormField(
readOnly: true,
// Stop keyboard from appearing
decoration: InputDecoration(
labelText: i18n.date,
// suffixIcon: const Icon(Icons.calendar_today),
),
enableInteractiveSelection: false,
controller: _dateController,
onTap: () async {
// Show Date Picker Here
final pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year - 10),
lastDate: DateTime.now(),
);
if (pickedDate != null) {
_dateController.text = dateFormat.format(pickedDate);
}
},
onSaved: (newValue) {
_dateController.text = newValue!;
},
child: DateInputWidget(
value: _date,
labelText: i18n.date,
firstDate: DateTime(DateTime.now().year - 10),
lastDate: DateTime.now(),
onChanged: (date) => _date = date,
),
),
if (widget.withDate)
Expanded(
child: TextFormField(
child: TimeInputWidget(
key: const Key('field-time'),
decoration: InputDecoration(
labelText: i18n.time,
//suffixIcon: const Icon(Icons.punch_clock)
),
controller: _timeController,
onTap: () async {
// Stop keyboard from appearing
FocusScope.of(context).requestFocus(FocusNode());
// Open time picker
final pickedTime = await showTimePicker(
context: context,
initialTime: stringToTime(_timeController.text),
);
if (pickedTime != null) {
_timeController.text = timeToString(pickedTime)!;
}
},
onSaved: (newValue) {
_timeController.text = newValue!;
},
value: _time,
labelText: i18n.time,
onChanged: (time) => _time = time,
),
),
],
@@ -419,8 +353,12 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
_form.currentState!.save();
_mealItem.ingredientId = int.parse(_ingredientIdController.text);
final loggedDate = dateTimeFormat.parse(
'${_dateController.text} ${_timeController.text}',
final loggedDate = DateTime(
_date.year,
_date.month,
_date.day,
_time.hour,
_time.minute,
);
widget.onSave(context, ref, _mealItem, loggedDate);
@@ -714,44 +652,44 @@ class _PlanFormState extends ConsumerState<PlanForm> {
if (_goalType == GoalType.basic || _goalType == GoalType.advanced)
Column(
children: [
GoalMacros(
val: widget._plan.goalEnergy?.toString(),
label: AppLocalizations.of(context).goalEnergy,
suffix: AppLocalizations.of(context).kcal,
onSave: (double value) => widget._plan.goalEnergy = value,
DecimalInputWidget(
key: const Key('field-goal-energy'),
value: widget._plan.goalEnergy,
labelText: AppLocalizations.of(context).goalEnergy,
suffixText: AppLocalizations.of(context).kcal,
onChanged: (value) => widget._plan.goalEnergy = value,
),
GoalMacros(
val: widget._plan.goalProtein?.toString(),
label: AppLocalizations.of(context).goalProtein,
suffix: AppLocalizations.of(context).g,
onSave: (double value) => widget._plan.goalProtein = value,
DecimalInputWidget(
key: const Key('field-goal-protein'),
value: widget._plan.goalProtein,
labelText: AppLocalizations.of(context).goalProtein,
suffixText: AppLocalizations.of(context).g,
onChanged: (value) => widget._plan.goalProtein = value,
),
GoalMacros(
val: widget._plan.goalCarbohydrates?.toString(),
label: AppLocalizations.of(context).goalCarbohydrates,
suffix: AppLocalizations.of(context).g,
onSave: (double value) => widget._plan.goalCarbohydrates = value,
DecimalInputWidget(
key: const Key('field-goal-carbohydrates'),
value: widget._plan.goalCarbohydrates,
labelText: AppLocalizations.of(context).goalCarbohydrates,
suffixText: AppLocalizations.of(context).g,
onChanged: (value) => widget._plan.goalCarbohydrates = value,
),
GoalMacros(
val: widget._plan.goalFat?.toString(),
label: AppLocalizations.of(context).goalFat,
suffix: AppLocalizations.of(context).g,
onSave: (double value) => widget._plan.goalFat = value,
DecimalInputWidget(
key: const Key('field-goal-fat'),
value: widget._plan.goalFat,
labelText: AppLocalizations.of(context).goalFat,
suffixText: AppLocalizations.of(context).g,
onChanged: (value) => widget._plan.goalFat = value,
),
],
),
if (_goalType == GoalType.advanced)
GoalMacros(
val: widget._plan.goalFiber?.toString(),
label: AppLocalizations.of(context).goalFiber,
suffix: AppLocalizations.of(context).g,
onSave: (double value) => widget._plan.goalFiber = value,
DecimalInputWidget(
key: const Key('field-goal-fiber'),
value: widget._plan.goalFiber,
labelText: AppLocalizations.of(context).goalFiber,
suffixText: AppLocalizations.of(context).g,
onChanged: (value) => widget._plan.goalFiber = value,
),
ElevatedButton(
key: const Key(SUBMIT_BUTTON_KEY_NAME),
@@ -787,46 +725,3 @@ class _PlanFormState extends ConsumerState<PlanForm> {
);
}
}
class GoalMacros extends StatelessWidget {
const GoalMacros({
super.key,
required this.label,
required this.suffix,
required this.onSave,
this.val,
});
final String label;
final String suffix;
final Function(double) onSave;
final String? val;
@override
Widget build(BuildContext context) {
final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString());
return TextFormField(
initialValue: val ?? '',
decoration: InputDecoration(labelText: label, suffixText: suffix),
keyboardType: textInputTypeDecimal,
onSaved: (newValue) {
if (newValue == null || newValue == '') {
return;
}
onSave(numberFormat.parse(newValue) as double);
},
validator: (value) {
if (value == '') {
return null;
}
try {
numberFormat.parse(value!);
} catch (error) {
return AppLocalizations.of(context).enterValidNumber;
}
return null;
},
);
}
}

View File

@@ -23,7 +23,6 @@ import 'package:wger/helpers/consts.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/nutrition/meal.dart';
import 'package:wger/models/nutrition/meal_item.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/nutrition_notifier.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/screens/log_meal_screen.dart';
@@ -87,7 +86,6 @@ class _MealWidgetState extends ConsumerState<MealWidget> {
@override
Widget build(BuildContext context) {
final isOnline = ref.watch(networkStatusProvider);
return Container(
padding: const EdgeInsets.all(3),
child: Card(
@@ -112,19 +110,17 @@ class _MealWidgetState extends ConsumerState<MealWidget> {
TextButton.icon(
icon: const Icon(Icons.add),
label: Text(AppLocalizations.of(context).addIngredient),
onPressed: isOnline
? () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).addIngredient,
getMealItemForm(widget._meal, widget._recentMealItems),
hasListView: true,
),
);
}
: null,
onPressed: () {
Navigator.pushNamed(
context,
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).addIngredient,
getMealItemForm(widget._meal, widget._recentMealItems),
hasListView: true,
),
);
},
),
TextButton.icon(
label: Text(AppLocalizations.of(context).edit),

View File

@@ -22,7 +22,6 @@ import 'package:intl/intl.dart';
import 'package:wger/helpers/measurements.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/providers/body_weight_notifier.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/nutrition_notifier.dart';
import 'package:wger/providers/user_profile_notifier.dart';
import 'package:wger/screens/nutritional_plan_screen.dart';
@@ -100,7 +99,6 @@ class NutritionalPlansList extends riverpod.ConsumerWidget {
Widget build(BuildContext context, riverpod.WidgetRef ref) {
final plansAsync = ref.watch(nutritionProvider);
final notifier = ref.read(nutritionProvider.notifier);
final isOnline = ref.watch(networkStatusProvider);
return AsyncValueWidget<NutritionState>(
value: plansAsync,
@@ -153,56 +151,54 @@ class NutritionalPlansList extends riverpod.ConsumerWidget {
IconButton(
icon: const Icon(Icons.delete),
tooltip: AppLocalizations.of(context).delete,
onPressed: isOnline
? () async {
// Delete the plan from DB
await showDialog(
context: context,
builder: (BuildContext contextDialog) {
return AlertDialog(
content: Text(
AppLocalizations.of(
context,
).confirmDelete(currentPlan.description),
onPressed: () async {
// Delete the plan from DB
await showDialog(
context: context,
builder: (BuildContext contextDialog) {
return AlertDialog(
content: Text(
AppLocalizations.of(
context,
).confirmDelete(currentPlan.description),
),
actions: [
TextButton(
child: Text(
MaterialLocalizations.of(context).cancelButtonLabel,
),
onPressed: () => Navigator.of(contextDialog).pop(),
),
TextButton(
child: Text(
AppLocalizations.of(context).delete,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
actions: [
TextButton(
child: Text(
MaterialLocalizations.of(context).cancelButtonLabel,
),
onPressed: () => Navigator.of(contextDialog).pop(),
),
TextButton(
child: Text(
AppLocalizations.of(context).delete,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
onPressed: () {
// Confirmed, delete the plan
notifier.deletePlan(currentPlan.id!);
),
onPressed: () {
// Confirmed, delete the plan
notifier.deletePlan(currentPlan.id!);
// Close the popup
Navigator.of(contextDialog).pop();
// Close the popup
Navigator.of(contextDialog).pop();
// and inform the user
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context).successfullyDeleted,
textAlign: TextAlign.center,
),
),
);
},
// and inform the user
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context).successfullyDeleted,
textAlign: TextAlign.center,
),
),
],
);
},
);
}
: null,
);
},
),
],
);
},
);
},
),
],
),

View File

@@ -108,7 +108,6 @@ class RoutineDetailAppBar extends ConsumerWidget implements PreferredSizeWidget
),
PopupMenuItem<_RoutineDetailBarOptions>(
value: _RoutineDetailBarOptions.delete,
enabled: isOnline,
child: Text(i18n.delete),
),
];

View File

@@ -7,7 +7,7 @@ import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/workouts/day.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/routines_notifier.dart';
import 'package:wger/widgets/core/progress_indicator.dart';
import 'package:wger/widgets/core/form_submit_button.dart';
import 'package:wger/widgets/routines/forms/slot.dart';
class ReorderableDaysList extends ConsumerStatefulWidget {
@@ -183,11 +183,8 @@ class DayFormWidget extends ConsumerStatefulWidget {
}
class _DayFormWidgetState extends ConsumerState<DayFormWidget> {
Widget errorMessage = const SizedBox.shrink();
final descriptionController = TextEditingController();
final nameController = TextEditingController();
bool isSaving = false;
final _form = GlobalKey<FormState>();
@@ -214,7 +211,6 @@ class _DayFormWidgetState extends ConsumerState<DayFormWidget> {
key: _form,
child: Column(
children: [
errorMessage,
Text(
widget.day.isRest ? i18n.restDay : widget.day.name,
style: Theme.of(context).textTheme.titleLarge,
@@ -319,41 +315,18 @@ class _DayFormWidgetState extends ConsumerState<DayFormWidget> {
},
),
const SizedBox(height: 5),
ElevatedButton(
FormSubmitButton(
key: const Key(SUBMIT_BUTTON_KEY_NAME),
onPressed: isSaving || !isOnline
? null
: () async {
if (!_form.currentState!.validate()) {
return;
}
_form.currentState!.save();
setState(() => isSaving = true);
enabled: isOnline,
label: AppLocalizations.of(context).save,
onPressed: () async {
if (!_form.currentState!.validate()) {
return;
}
_form.currentState!.save();
try {
await ref.read(routinesRiverpodProvider.notifier).editDay(widget.day);
if (context.mounted) {
setState(() {
errorMessage = const SizedBox.shrink();
});
}
} on WgerHttpException catch (error) {
if (context.mounted) {
setState(() {
errorMessage = FormHttpErrorsWidget(error);
});
}
} finally {
if (mounted) {
setState(() {
isSaving = false;
});
}
}
},
child: isSaving
? const FormProgressIndicator()
: Text(AppLocalizations.of(context).save),
await ref.read(routinesRiverpodProvider.notifier).editDay(widget.day);
},
),
const SizedBox(height: 5),
ReorderableSlotList(widget.day.slots, widget.day),

View File

@@ -19,15 +19,13 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/errors.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/workouts/routine.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/routines_notifier.dart';
import 'package:wger/screens/routine_edit_screen.dart';
import 'package:wger/widgets/core/progress_indicator.dart';
import 'package:wger/widgets/core/form_submit_button.dart';
class RoutineForm extends ConsumerStatefulWidget {
final Routine _routine;
@@ -41,9 +39,7 @@ class RoutineForm extends ConsumerStatefulWidget {
class _RoutineFormState extends ConsumerState<RoutineForm> {
final _form = GlobalKey<FormState>();
Widget errorMessage = const SizedBox.shrink();
bool isSaving = false;
late bool fitInWeek;
late DateTime startDate;
late DateTime endDate;
@@ -73,7 +69,6 @@ class _RoutineFormState extends ConsumerState<RoutineForm> {
final isOnline = ref.watch(networkStatusProvider);
final children = [
errorMessage,
TextFormField(
key: const Key('field-name'),
decoration: InputDecoration(labelText: i18n.name),
@@ -219,54 +214,33 @@ class _RoutineFormState extends ConsumerState<RoutineForm> {
},
),
const SizedBox(height: 5),
ElevatedButton(
// Creating a routine needs the server to assign an integer PK; editing an
// existing one syncs through PowerSync and works offline.
FormSubmitButton(
key: const Key(SUBMIT_BUTTON_KEY_NAME),
onPressed: isSaving || !isOnline
? null
: () async {
// Validate and save
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
setState(() {
isSaving = true;
});
enabled: !(widget._routine.id == null && !isOnline),
label: AppLocalizations.of(context).save,
onPressed: () async {
// Validate and save
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
// Save to DB
try {
final routinesProvider = ref.read(routinesRiverpodProvider.notifier);
if (widget._routine.id != null) {
await routinesProvider.editRoutine(widget._routine);
} else {
final routine = await routinesProvider.addRoutine(widget._routine);
if (context.mounted) {
Navigator.of(context).pushReplacementNamed(
RoutineEditScreen.routeName,
arguments: routine.id,
);
}
}
setState(() {
errorMessage = const SizedBox.shrink();
});
} on WgerHttpException catch (error) {
if (context.mounted) {
setState(() {
errorMessage = FormHttpErrorsWidget(error);
});
}
} finally {
if (mounted) {
setState(() {
isSaving = false;
});
}
}
},
child: isSaving ? const FormProgressIndicator() : Text(AppLocalizations.of(context).save),
final routinesProvider = ref.read(routinesRiverpodProvider.notifier);
if (widget._routine.id != null) {
await routinesProvider.editRoutine(widget._routine);
} else {
final routine = await routinesProvider.addRoutine(widget._routine);
if (context.mounted) {
Navigator.of(context).pushReplacementNamed(
RoutineEditScreen.routeName,
arguments: routine.id,
);
}
}
},
),
];
return Form(

View File

@@ -22,10 +22,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/helpers/errors.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/workouts/session.dart';
import 'package:wger/providers/workout_session_notifier.dart';
import 'package:wger/widgets/core/datetime_input.dart';
class SessionForm extends ConsumerStatefulWidget {
final _logger = Logger('SessionForm');
@@ -55,27 +55,16 @@ class _SessionFormState extends ConsumerState<SessionForm> {
final _form = GlobalKey<FormState>();
final notesController = TextEditingController();
final timeStartController = TextEditingController();
final timeEndController = TextEditingController();
@override
void initState() {
super.initState();
timeStartController.text = widget._session.timeStart == null
? ''
: timeToString(widget._session.timeStart)!;
timeEndController.text = widget._session.timeEnd == null
? ''
: timeToString(widget._session.timeEnd)!;
notesController.text = widget._session.notes ?? '';
}
@override
void dispose() {
notesController.dispose();
timeStartController.dispose();
timeEndController.dispose();
super.dispose();
}
@@ -122,97 +111,29 @@ class _SessionFormState extends ConsumerState<SessionForm> {
spacing: 10,
children: [
Flexible(
child: TextFormField(
child: TimeInputWidget(
key: const ValueKey('time-start'),
decoration: InputDecoration(
labelText: AppLocalizations.of(context).timeStart,
errorMaxLines: 2,
suffix: IconButton(
onPressed: () => {
setState(() {
timeStartController.text = '';
widget._session.timeStart = null;
}),
},
icon: const Icon(Icons.clear),
),
),
controller: timeStartController,
onFieldSubmitted: (_) {},
onTap: () async {
// Stop keyboard from appearing
FocusScope.of(context).requestFocus(FocusNode());
// Open time picker
final pickedTime = await showTimePicker(
context: context,
initialTime: widget._session.timeStart ?? TimeOfDay.now(),
);
if (pickedTime != null) {
timeStartController.text = timeToString(pickedTime)!;
widget._session.timeStart = pickedTime;
}
},
onSaved: (newValue) {
if (newValue != null && newValue.isNotEmpty) {
widget._session.timeStart = stringToTime(newValue);
}
},
value: widget._session.timeStart,
labelText: AppLocalizations.of(context).timeStart,
onCleared: () => widget._session.timeStart = null,
onChanged: (time) => widget._session.timeStart = time,
validator: (_) {
if (timeStartController.text.isEmpty && timeEndController.text.isEmpty) {
return null;
final start = widget._session.timeStart;
final end = widget._session.timeEnd;
if (start != null && end != null && start.isAfter(end)) {
return AppLocalizations.of(context).timeStartAhead;
}
if (timeStartController.text.isNotEmpty && timeEndController.text.isNotEmpty) {
final TimeOfDay startTime = stringToTime(timeStartController.text);
final TimeOfDay endTime = stringToTime(timeEndController.text);
if (startTime.isAfter(endTime)) {
return AppLocalizations.of(context).timeStartAhead;
}
}
return null;
},
),
),
Flexible(
child: TextFormField(
child: TimeInputWidget(
key: const ValueKey('time-end'),
decoration: InputDecoration(
labelText: AppLocalizations.of(context).timeEnd,
suffix: IconButton(
onPressed: () => {
setState(() {
timeEndController.text = '';
widget._session.timeEnd = null;
}),
},
icon: const Icon(Icons.clear),
),
),
controller: timeEndController,
onFieldSubmitted: (_) {},
onTap: () async {
// Stop keyboard from appearing
FocusScope.of(context).requestFocus(FocusNode());
// Open time picker
final pickedTime = await showTimePicker(
context: context,
initialTime: widget._session.timeEnd ?? TimeOfDay.now(),
);
if (pickedTime != null) {
timeEndController.text = timeToString(pickedTime)!;
widget._session.timeEnd = pickedTime;
}
},
onSaved: (newValue) {
if (newValue != null && newValue.isNotEmpty) {
widget._session.timeEnd = stringToTime(newValue);
}
},
value: widget._session.timeEnd,
labelText: AppLocalizations.of(context).timeEnd,
onCleared: () => widget._session.timeEnd = null,
onChanged: (time) => widget._session.timeEnd = time,
),
),
],

View File

@@ -28,6 +28,8 @@ import 'package:wger/models/workouts/slot.dart';
import 'package:wger/models/workouts/slot_entry.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/routines_notifier.dart';
import 'package:wger/widgets/core/decimal_input.dart';
import 'package:wger/widgets/core/form_submit_button.dart';
import 'package:wger/widgets/core/progress_indicator.dart';
import 'package:wger/widgets/exercises/autocompleter.dart';
import 'package:wger/widgets/routines/forms/repetitions.dart';
@@ -47,17 +49,16 @@ class SlotEntryForm extends ConsumerStatefulWidget {
}
class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
bool isSaving = false;
bool isDeleting = false;
final iconSize = 18.0;
double setsSliderValue = 1.0;
final weightController = TextEditingController();
final maxWeightController = TextEditingController();
final repetitionsController = TextEditingController();
final maxRepetitionsController = TextEditingController();
num? _weight;
num? _maxWeight;
num? _reps;
num? _maxReps;
final restController = TextEditingController();
final maxRestController = TextEditingController();
final rirController = TextEditingController();
@@ -68,27 +69,35 @@ class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
var _edit = false;
bool _controllersInitialized = false;
@override
void initState() {
super.initState();
if (widget.entry.nrOfSetsConfigs.isNotEmpty) {
setsSliderValue = widget.entry.nrOfSetsConfigs.first.value.toDouble();
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_controllersInitialized) {
return;
}
_controllersInitialized = true;
if (widget.entry.weightConfigs.isNotEmpty) {
weightController.text = widget.entry.weightConfigs.first.value.toString();
_weight = widget.entry.weightConfigs.first.value;
}
if (widget.entry.maxWeightConfigs.isNotEmpty) {
maxWeightController.text = widget.entry.maxWeightConfigs.first.value.toString();
_maxWeight = widget.entry.maxWeightConfigs.first.value;
}
if (widget.entry.repetitionsConfigs.isNotEmpty) {
repetitionsController.text = widget.entry.repetitionsConfigs.first.value.round().toString();
_reps = widget.entry.repetitionsConfigs.first.value;
}
if (widget.entry.maxRepetitionsConfigs.isNotEmpty) {
maxRepetitionsController.text = widget.entry.maxRepetitionsConfigs.first.value
.round()
.toString();
_maxReps = widget.entry.maxRepetitionsConfigs.first.value;
}
if (widget.entry.restTimeConfigs.isNotEmpty) {
@@ -99,18 +108,13 @@ class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
}
if (widget.entry.rirConfigs.isNotEmpty) {
rirController.text = widget.entry.rirConfigs.first.value.round().toString();
// RiR uses 0.5 steps, so the fractional part must be kept
rirController.text = widget.entry.rirConfigs.first.value.toString();
}
}
@override
void dispose() {
weightController.dispose();
maxWeightController.dispose();
repetitionsController.dispose();
maxRepetitionsController.dispose();
restController.dispose();
maxRestController.dispose();
@@ -228,32 +232,20 @@ class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
spacing: 10,
children: [
Flexible(
child: TextFormField(
child: DecimalInputWidget(
key: const ValueKey('field-weight'),
controller: weightController,
keyboardType: textInputTypeDecimal,
decoration: InputDecoration(labelText: i18n.weight),
validator: (value) {
if (value != null && value != '' && numberFormat.tryParse(value) == null) {
return i18n.enterValidNumber;
}
return null;
},
value: _weight,
labelText: i18n.weight,
onChanged: (v) => _weight = v,
),
),
if (!widget.simpleMode)
Flexible(
child: TextFormField(
child: DecimalInputWidget(
key: const ValueKey('field-max-weight'),
controller: maxWeightController,
keyboardType: textInputTypeDecimal,
decoration: InputDecoration(labelText: i18n.max),
validator: (value) {
if (value != null && value != '' && numberFormat.tryParse(value) == null) {
return i18n.enterValidNumber;
}
return null;
},
value: _maxWeight,
labelText: i18n.max,
onChanged: (v) => _maxWeight = v,
),
),
],
@@ -270,32 +262,20 @@ class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
spacing: 10,
children: [
Flexible(
child: TextFormField(
child: DecimalInputWidget(
key: const ValueKey('field-repetitions'),
controller: repetitionsController,
keyboardType: textInputTypeDecimal,
decoration: InputDecoration(labelText: i18n.repetitions),
validator: (value) {
if (value != null && value != '' && numberFormat.tryParse(value) == null) {
return i18n.enterValidNumber;
}
return null;
},
value: _reps,
labelText: i18n.repetitions,
onChanged: (v) => _reps = v,
),
),
if (!widget.simpleMode)
Flexible(
child: TextFormField(
child: DecimalInputWidget(
key: const ValueKey('field-max-repetitions'),
controller: maxRepetitionsController,
keyboardType: textInputTypeDecimal,
decoration: InputDecoration(labelText: i18n.max),
validator: (value) {
if (value != null && value != '' && numberFormat.tryParse(value) == null) {
return i18n.enterValidNumber;
}
return null;
},
value: _maxReps,
labelText: i18n.max,
onChanged: (v) => _maxReps = v,
),
),
],
@@ -340,82 +320,46 @@ class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
onChanged: (value) => rirController.text = value,
),
const SizedBox(height: 5),
OutlinedButton(
FormSubmitButton(
key: const Key(SUBMIT_BUTTON_KEY_NAME),
onPressed: isSaving || !isOnline
? null
: () async {
if (!_form.currentState!.validate()) {
return;
}
_form.currentState!.save();
setState(() => isSaving = true);
enabled: isOnline,
label: AppLocalizations.of(context).save,
onPressed: () async {
if (!_form.currentState!.validate()) {
return;
}
_form.currentState!.save();
// Process new, edited or entries to be deleted
try {
await Future.wait([
provider.handleConfig(
widget.entry,
setsSliderValue == 0 ? null : setsSliderValue.round(),
ConfigType.sets,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(weightController.text),
ConfigType.weight,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(maxWeightController.text),
ConfigType.maxWeight,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(repetitionsController.text),
ConfigType.repetitions,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(maxRepetitionsController.text),
ConfigType.maxRepetitions,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(restController.text),
ConfigType.rest,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(maxRestController.text),
ConfigType.maxRest,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(rirController.text),
ConfigType.rir,
),
]);
await provider.editSlotEntry(widget.entry, widget.routineId);
if (mounted) {
setState(() => isSaving = false);
errorMessage = const SizedBox.shrink();
}
} on WgerHttpException catch (error) {
if (context.mounted) {
setState(() {
errorMessage = FormHttpErrorsWidget(error);
});
}
} finally {
if (mounted) {
setState(() => isSaving = false);
}
}
},
child: isSaving
? const FormProgressIndicator()
: Text(AppLocalizations.of(context).save),
// Process new, edited or entries to be deleted
await Future.wait([
provider.handleConfig(
widget.entry,
setsSliderValue == 0 ? null : setsSliderValue.round(),
ConfigType.sets,
),
provider.handleConfig(widget.entry, _weight, ConfigType.weight),
provider.handleConfig(widget.entry, _maxWeight, ConfigType.maxWeight),
provider.handleConfig(widget.entry, _reps, ConfigType.repetitions),
provider.handleConfig(widget.entry, _maxReps, ConfigType.maxRepetitions),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(restController.text),
ConfigType.rest,
),
provider.handleConfig(
widget.entry,
numberFormat.tryParse(maxRestController.text),
ConfigType.maxRest,
),
provider.handleConfig(
widget.entry,
// RiR is slider-driven and held as an invariant string
num.tryParse(rirController.text),
ConfigType.rir,
),
]);
await provider.editSlotEntry(widget.entry, widget.routineId);
},
),
const SizedBox(height: 10),
],

View File

@@ -251,12 +251,10 @@ class LogsPastLogsWidget extends ConsumerWidget {
}
class LogFormWidget extends ConsumerStatefulWidget {
final _logger = Logger('LogFormWidget');
final PageController controller;
final SetConfigData configData;
LogFormWidget({
const LogFormWidget({
super.key,
required this.controller,
required this.configData,

View File

@@ -105,11 +105,10 @@ class _WorkoutSummaryState extends ConsumerState<WorkoutSummary> {
}
class WorkoutSessionStats extends ConsumerWidget {
final _logger = Logger('WorkoutSessionStats');
final WorkoutSession? _session;
final List<UserTrophy> _userPrTrophies;
WorkoutSessionStats(this._session, this._userPrTrophies, {super.key});
const WorkoutSessionStats(this._session, this._userPrTrophies, {super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {

View File

@@ -20,7 +20,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/providers/network_provider.dart';
import 'package:wger/providers/routines_notifier.dart';
import 'package:wger/screens/routine_screen.dart';
import 'package:wger/widgets/core/async_value_widget.dart';
@@ -38,7 +37,6 @@ class _RoutinesListState extends ConsumerState<RoutinesList> {
@override
Widget build(BuildContext context) {
final isOnline = ref.watch(networkStatusProvider);
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
final routineProvider = ref.read(routinesRiverpodProvider.notifier);
final routinesAsync = ref.watch(routinesRiverpodProvider);
@@ -96,58 +94,56 @@ class _RoutinesListState extends ConsumerState<RoutinesList> {
IconButton(
icon: const Icon(Icons.delete),
tooltip: AppLocalizations.of(context).delete,
onPressed: isOnline
? () async {
// Delete workout from DB
await showDialog(
context: context,
builder: (BuildContext contextDialog) {
return AlertDialog(
content: Text(
AppLocalizations.of(
context,
).confirmDelete(currentRoutine.name),
onPressed: () async {
// Delete workout from DB
await showDialog(
context: context,
builder: (BuildContext contextDialog) {
return AlertDialog(
content: Text(
AppLocalizations.of(
context,
).confirmDelete(currentRoutine.name),
),
actions: [
TextButton(
child: Text(
MaterialLocalizations.of(context).cancelButtonLabel,
),
onPressed: () => Navigator.of(contextDialog).pop(),
),
TextButton(
child: Text(
AppLocalizations.of(context).delete,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
actions: [
TextButton(
child: Text(
MaterialLocalizations.of(context).cancelButtonLabel,
),
onPressed: () => Navigator.of(contextDialog).pop(),
),
TextButton(
child: Text(
AppLocalizations.of(context).delete,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
onPressed: () {
// Confirmed, delete the workout
routineProvider.deleteRoutine(currentRoutine.id!);
),
onPressed: () {
// Confirmed, delete the workout
routineProvider.deleteRoutine(currentRoutine.id!);
// Close the popup
Navigator.of(contextDialog).pop();
// Close the popup
Navigator.of(contextDialog).pop();
// and inform the user
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(
context,
).successfullyDeleted,
textAlign: TextAlign.center,
),
),
);
},
// and inform the user
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(
context,
).successfullyDeleted,
textAlign: TextAlign.center,
),
),
],
);
},
);
}
: null,
);
},
),
],
);
},
);
},
),
],
),

View File

@@ -24,11 +24,10 @@ import 'package:wger/helpers/consts.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/body_weight/weight_entry.dart';
import 'package:wger/providers/body_weight_notifier.dart';
import 'package:wger/widgets/core/datetime_input.dart';
class WeightForm extends riverpod.ConsumerWidget {
final _form = GlobalKey<FormState>();
final dateController = TextEditingController(text: '');
final timeController = TextEditingController(text: '');
final weightController = TextEditingController(text: '');
final WeightEntry _weightEntry;
@@ -39,50 +38,22 @@ class WeightForm extends riverpod.ConsumerWidget {
@override
Widget build(BuildContext context, riverpod.WidgetRef ref) {
final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString());
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
final timeFormat = DateFormat.Hm(Localizations.localeOf(context).languageCode);
if (weightController.text.isEmpty && _weightEntry.weight != 0) {
weightController.text = numberFormat.format(_weightEntry.weight);
}
if (dateController.text.isEmpty) {
dateController.text = dateFormat.format(_weightEntry.date);
}
if (timeController.text.isEmpty) {
timeController.text = TimeOfDay.fromDateTime(_weightEntry.date).format(context);
}
return Form(
key: _form,
child: Column(
children: [
TextFormField(
DateInputWidget(
key: const Key('dateInput'),
// Stop keyboard from appearing
readOnly: true,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).date,
suffixIcon: const Icon(
Icons.calendar_today,
key: Key('calendarIcon'),
),
),
enableInteractiveSelection: false,
controller: dateController,
onTap: () async {
final pickedDate = await showDatePicker(
context: context,
initialDate: _weightEntry.date,
firstDate: DateTime(DateTime.now().year - 10),
lastDate: DateTime.now(),
);
if (pickedDate != null) {
dateController.text = dateFormat.format(pickedDate);
}
},
onSaved: (newValue) {
final date = dateFormat.parse(newValue!);
value: _weightEntry.date,
labelText: AppLocalizations.of(context).date,
firstDate: DateTime(DateTime.now().year - 10),
lastDate: DateTime.now(),
onChanged: (date) {
_weightEntry.date = _weightEntry.date.copyWith(
year: date.year,
month: date.month,
@@ -90,35 +61,15 @@ class WeightForm extends riverpod.ConsumerWidget {
);
},
),
TextFormField(
TimeInputWidget(
key: const Key('timeInput'),
// Stop keyboard from appearing
readOnly: true,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).time,
suffixIcon: const Icon(
Icons.access_time_outlined,
key: Key('clockIcon'),
),
),
enableInteractiveSelection: false,
controller: timeController,
onTap: () async {
final pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(_weightEntry.date),
);
if (pickedTime != null) {
timeController.text = pickedTime.format(context);
}
},
onSaved: (newValue) {
final time = timeFormat.parse(newValue!);
value: TimeOfDay.fromDateTime(_weightEntry.date),
labelText: AppLocalizations.of(context).time,
onChanged: (time) {
_weightEntry.date = _weightEntry.date.copyWith(
hour: time.hour,
minute: time.minute,
second: time.second,
second: 0,
);
},
),