From dc5bd1e975eca95fefd0bd5aeeb7bb890cd763d0 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 21 May 2026 00:11:40 +0200 Subject: [PATCH] Consolidate localized number edit logic into its own widgets --- lib/widgets/core/decimal_input.dart | 79 ++++++++++++++ lib/widgets/measurements/forms.dart | 40 ++----- lib/widgets/nutrition/forms.dart | 94 +++++------------ lib/widgets/routines/forms/slot_entry.dart | 94 ++++++----------- test/core/decimal_input_test.dart | 116 +++++++++++++++++++++ 5 files changed, 257 insertions(+), 166 deletions(-) create mode 100644 lib/widgets/core/decimal_input.dart create mode 100644 test/core/decimal_input_test.dart diff --git a/lib/widgets/core/decimal_input.dart b/lib/widgets/core/decimal_input.dart new file mode 100644 index 000000000..f481a7a5a --- /dev/null +++ b/lib/widgets/core/decimal_input.dart @@ -0,0 +1,79 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +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 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; + }, + ); + } +} diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index 8aec681f1..b790b988a 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -18,13 +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'; @@ -120,7 +119,6 @@ class MeasurementEntryForm extends ConsumerStatefulWidget { class _MeasurementEntryFormState extends ConsumerState { final _form = GlobalKey(); - final _valueController = TextEditingController(); final _notesController = TextEditingController(); late final String? _existingId = widget._entry?.id; @@ -138,7 +136,6 @@ class _MeasurementEntryFormState extends ConsumerState { @override void dispose() { - _valueController.dispose(); _notesController.dispose(); super.dispose(); } @@ -150,13 +147,6 @@ class _MeasurementEntryFormState extends ConsumerState { widget._categoryId, ); - 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) { @@ -205,28 +195,12 @@ class _MeasurementEntryFormState extends ConsumerState { ), // 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( diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index defe8a74e..8fe52ea40 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -30,6 +30,7 @@ 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'; @@ -651,44 +652,44 @@ class _PlanFormState extends ConsumerState { 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), @@ -724,46 +725,3 @@ class _PlanFormState extends ConsumerState { ); } } - -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; - }, - ); - } -} diff --git a/lib/widgets/routines/forms/slot_entry.dart b/lib/widgets/routines/forms/slot_entry.dart index ea39a8b54..be7ea9a54 100644 --- a/lib/widgets/routines/forms/slot_entry.dart +++ b/lib/widgets/routines/forms/slot_entry.dart @@ -28,6 +28,7 @@ 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/progress_indicator.dart'; import 'package:wger/widgets/exercises/autocompleter.dart'; import 'package:wger/widgets/routines/forms/repetitions.dart'; @@ -54,10 +55,10 @@ class _SlotEntryFormState extends ConsumerState { 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(); @@ -76,19 +77,16 @@ class _SlotEntryFormState extends ConsumerState { } 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) { @@ -105,12 +103,6 @@ class _SlotEntryFormState extends ConsumerState { @override void dispose() { - weightController.dispose(); - maxWeightController.dispose(); - - repetitionsController.dispose(); - maxRepetitionsController.dispose(); - restController.dispose(); maxRestController.dispose(); @@ -228,32 +220,20 @@ class _SlotEntryFormState extends ConsumerState { 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 +250,20 @@ class _SlotEntryFormState extends ConsumerState { 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, ), ), ], @@ -359,24 +327,20 @@ class _SlotEntryFormState extends ConsumerState { setsSliderValue == 0 ? null : setsSliderValue.round(), ConfigType.sets, ), + provider.handleConfig(widget.entry, _weight, ConfigType.weight), provider.handleConfig( widget.entry, - numberFormat.tryParse(weightController.text), - ConfigType.weight, - ), - provider.handleConfig( - widget.entry, - numberFormat.tryParse(maxWeightController.text), + _maxWeight, ConfigType.maxWeight, ), provider.handleConfig( widget.entry, - numberFormat.tryParse(repetitionsController.text), + _reps, ConfigType.repetitions, ), provider.handleConfig( widget.entry, - numberFormat.tryParse(maxRepetitionsController.text), + _maxReps, ConfigType.maxRepetitions, ), provider.handleConfig( diff --git a/test/core/decimal_input_test.dart b/test/core/decimal_input_test.dart new file mode 100644 index 000000000..de4755070 --- /dev/null +++ b/test/core/decimal_input_test.dart @@ -0,0 +1,116 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/widgets/core/decimal_input.dart'; + +void main() { + Widget wrap(Widget child, {String locale = 'en'}) { + return MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: child), + ); + } + + testWidgets('renders the value with the en decimal separator', (WidgetTester tester) async { + await tester.pumpWidget( + wrap(DecimalInputWidget(value: 12.5, labelText: 'X', onChanged: (_) {})), + ); + await tester.pumpAndSettle(); + + expect(find.text('12.5'), findsOneWidget); + }); + + testWidgets('renders the value with the de decimal separator', (WidgetTester tester) async { + await tester.pumpWidget( + wrap( + DecimalInputWidget(value: 12.5, labelText: 'X', onChanged: (_) {}), + locale: 'de', + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('12,5'), findsOneWidget); + }); + + testWidgets('reports the value parsed with the active locale', (WidgetTester tester) async { + num? captured = 0; + await tester.pumpWidget( + wrap( + DecimalInputWidget(value: null, labelText: 'X', onChanged: (v) => captured = v), + locale: 'de', + ), + ); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextFormField), '7,5'); + + expect(captured, 7.5); + }); + + testWidgets('reports null when the field is cleared', (WidgetTester tester) async { + num? captured = 1; + await tester.pumpWidget( + wrap(DecimalInputWidget(value: 5, labelText: 'X', onChanged: (v) => captured = v)), + ); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextFormField), ''); + + expect(captured, isNull); + }); + + testWidgets('a required empty field fails validation', (WidgetTester tester) async { + final formKey = GlobalKey(); + await tester.pumpWidget( + wrap( + Form( + key: formKey, + child: DecimalInputWidget( + value: null, + labelText: 'X', + isRequired: true, + onChanged: (_) {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(formKey.currentState!.validate(), isFalse); + }); + + testWidgets('an optional empty field passes validation', (WidgetTester tester) async { + final formKey = GlobalKey(); + await tester.pumpWidget( + wrap( + Form( + key: formKey, + child: DecimalInputWidget(value: null, labelText: 'X', onChanged: (_) {}), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(formKey.currentState!.validate(), isTrue); + }); +}