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