Consolidate localized number edit logic into its own widgets

This commit is contained in:
Roland Geider
2026-05-21 00:11:40 +02:00
parent c411e8949a
commit dc5bd1e975
5 changed files with 257 additions and 166 deletions

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

@@ -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<MeasurementEntryForm> {
final _form = GlobalKey<FormState>();
final _valueController = TextEditingController();
final _notesController = TextEditingController();
late final String? _existingId = widget._entry?.id;
@@ -138,7 +136,6 @@ class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
@override
void dispose() {
_valueController.dispose();
_notesController.dispose();
super.dispose();
}
@@ -150,13 +147,6 @@ class _MeasurementEntryFormState extends ConsumerState<MeasurementEntryForm> {
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<MeasurementEntryForm> {
),
// 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

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

@@ -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<SlotEntryForm> {
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<SlotEntryForm> {
}
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<SlotEntryForm> {
@override
void dispose() {
weightController.dispose();
maxWeightController.dispose();
repetitionsController.dispose();
maxRepetitionsController.dispose();
restController.dispose();
maxRestController.dispose();
@@ -228,32 +220,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 +250,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,
),
),
],
@@ -359,24 +327,20 @@ class _SlotEntryFormState extends ConsumerState<SlotEntryForm> {
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(

View File

@@ -0,0 +1,116 @@
/*
* 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_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<FormState>();
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<FormState>();
await tester.pumpWidget(
wrap(
Form(
key: formKey,
child: DecimalInputWidget(value: null, labelText: 'X', onChanged: (_) {}),
),
),
);
await tester.pumpAndSettle();
expect(formKey.currentState!.validate(), isTrue);
});
}