mirror of
https://github.com/wger-project/flutter.git
synced 2026-12-03 02:24:30 +01:00
Consolidate time and date picking logic into their own widgets
This makes it easier to fix things like localization, etc. in one place
This commit is contained in:
@@ -18,11 +18,10 @@
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:wger/helpers/json.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/models/nutrition/meal.dart';
|
||||
import 'package:wger/providers/nutrition_notifier.dart';
|
||||
import 'package:wger/widgets/core/datetime_input.dart';
|
||||
import 'package:wger/widgets/nutrition/meal.dart';
|
||||
import 'package:wger/widgets/nutrition/nutrition_tiles.dart';
|
||||
|
||||
@@ -44,27 +43,11 @@ class LogMealScreen extends ConsumerStatefulWidget {
|
||||
|
||||
class _LogMealScreenState extends ConsumerState<LogMealScreen> {
|
||||
double portionPct = 100;
|
||||
final _dateController = TextEditingController(text: '');
|
||||
final _timeController = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_timeController.text = timeToString(TimeOfDay.now())!;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_dateController.dispose();
|
||||
_timeController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
DateTime _date = DateTime.now();
|
||||
TimeOfDay _time = TimeOfDay.now();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode);
|
||||
final dateTimeFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode).add_Hm();
|
||||
final i18n = AppLocalizations.of(context);
|
||||
|
||||
final args = ModalRoute.of(context)!.settings.arguments as LogMealArguments;
|
||||
@@ -74,10 +57,6 @@ class _LogMealScreenState extends ConsumerState<LogMealScreen> {
|
||||
.toList(),
|
||||
);
|
||||
|
||||
if (_dateController.text.isEmpty) {
|
||||
_dateController.text = dateFormat.format(DateTime.now());
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(i18n.logMeal)),
|
||||
body: Consumer(
|
||||
@@ -120,50 +99,22 @@ class _LogMealScreenState extends ConsumerState<LogMealScreen> {
|
||||
children: [
|
||||
const Padding(padding: EdgeInsets.symmetric(horizontal: 12)),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
child: DateInputWidget(
|
||||
key: const ValueKey('field-date'),
|
||||
readOnly: true,
|
||||
decoration: InputDecoration(labelText: i18n.date),
|
||||
enableInteractiveSelection: false,
|
||||
controller: _dateController,
|
||||
onTap: () async {
|
||||
final pickedDate = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: DateTime.now(),
|
||||
firstDate: DateTime.now().subtract(const Duration(days: 3000)),
|
||||
lastDate: DateTime.now(),
|
||||
);
|
||||
|
||||
if (pickedDate != null) {
|
||||
_dateController.text = dateFormat.format(pickedDate);
|
||||
}
|
||||
},
|
||||
onSaved: (newValue) {
|
||||
_dateController.text = newValue!;
|
||||
},
|
||||
value: _date,
|
||||
labelText: i18n.date,
|
||||
firstDate: DateTime.now().subtract(const Duration(days: 3000)),
|
||||
lastDate: DateTime.now(),
|
||||
onChanged: (date) => _date = date,
|
||||
),
|
||||
),
|
||||
const Padding(padding: EdgeInsets.symmetric(horizontal: 12)),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
child: TimeInputWidget(
|
||||
key: const ValueKey('field-time'),
|
||||
readOnly: true,
|
||||
decoration: InputDecoration(labelText: i18n.time),
|
||||
controller: _timeController,
|
||||
onTap: () async {
|
||||
// Open time picker
|
||||
final pickedTime = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay.fromDateTime(DateTime.now()),
|
||||
);
|
||||
|
||||
if (pickedTime != null) {
|
||||
_timeController.text = timeToString(pickedTime)!;
|
||||
}
|
||||
},
|
||||
onSaved: (newValue) {
|
||||
_timeController.text = newValue!;
|
||||
},
|
||||
value: _time,
|
||||
labelText: i18n.time,
|
||||
onChanged: (time) => _time = time,
|
||||
),
|
||||
),
|
||||
const Padding(padding: EdgeInsets.symmetric(horizontal: 12)),
|
||||
@@ -177,8 +128,12 @@ class _LogMealScreenState extends ConsumerState<LogMealScreen> {
|
||||
TextButton(
|
||||
child: Text(i18n.save),
|
||||
onPressed: () async {
|
||||
final loggedDate = dateTimeFormat.parse(
|
||||
'${_dateController.text} ${_timeController.text}',
|
||||
final loggedDate = DateTime(
|
||||
_date.year,
|
||||
_date.month,
|
||||
_date.day,
|
||||
_time.hour,
|
||||
_time.minute,
|
||||
);
|
||||
await ref
|
||||
.read(nutritionProvider.notifier)
|
||||
|
||||
232
lib/widgets/core/datetime_input.dart
Normal file
232
lib/widgets/core/datetime_input.dart
Normal 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);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ 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/error.dart';
|
||||
import 'package:wger/widgets/core/progress_indicator.dart';
|
||||
|
||||
@@ -120,8 +121,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,29 +139,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
|
||||
@@ -190,77 +177,29 @@ 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,
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -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,7 @@ 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/nutrition/helpers.dart';
|
||||
import 'package:wger/widgets/nutrition/nutrition_tiles.dart';
|
||||
import 'package:wger/widgets/nutrition/widgets.dart';
|
||||
@@ -39,44 +39,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 +157,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 +169,6 @@ class IngredientFormState extends ConsumerState<IngredientForm> {
|
||||
_ingredientController.dispose();
|
||||
_ingredientIdController.dispose();
|
||||
_amountController.dispose();
|
||||
_dateController.dispose();
|
||||
_timeController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -227,20 +209,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
|
||||
@@ -337,58 +307,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 +352,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);
|
||||
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
134
test/core/datetime_input_test.dart
Normal file
134
test/core/datetime_input_test.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* 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/datetime_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),
|
||||
);
|
||||
}
|
||||
|
||||
group('TimeInputWidget', () {
|
||||
testWidgets('renders the value in a 12-hour locale', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
TimeInputWidget(
|
||||
value: const TimeOfDay(hour: 15, minute: 30),
|
||||
labelText: 'Time',
|
||||
onChanged: (_) {},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('3:30 PM'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('renders the value in a 24-hour locale', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
TimeInputWidget(
|
||||
value: const TimeOfDay(hour: 15, minute: 30),
|
||||
labelText: 'Time',
|
||||
onChanged: (_) {},
|
||||
),
|
||||
locale: 'de',
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('15:30'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('shows nothing when the value is null', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
wrap(TimeInputWidget(value: null, labelText: 'Time', onChanged: (_) {})),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byIcon(Icons.clear), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('clear button invokes onCleared and clears the display', (
|
||||
WidgetTester tester,
|
||||
) async {
|
||||
var cleared = false;
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
TimeInputWidget(
|
||||
value: const TimeOfDay(hour: 15, minute: 30),
|
||||
labelText: 'Time',
|
||||
onChanged: (_) {},
|
||||
onCleared: () => cleared = true,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('3:30 PM'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.clear));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(cleared, isTrue);
|
||||
expect(find.text('3:30 PM'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
group('DateInputWidget', () {
|
||||
testWidgets('renders the value localized', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
DateInputWidget(
|
||||
value: DateTime(2021, 1, 5),
|
||||
labelText: 'Date',
|
||||
onChanged: (_) {},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('1/5/2021'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('renders the value localized for a comma-decimal locale', (
|
||||
WidgetTester tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
DateInputWidget(
|
||||
value: DateTime(2021, 1, 5),
|
||||
labelText: 'Date',
|
||||
onChanged: (_) {},
|
||||
),
|
||||
locale: 'de',
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('5.1.2021'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -22,7 +22,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/mockito.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/meal.dart';
|
||||
import 'package:wger/models/nutrition/nutritional_plan.dart';
|
||||
@@ -111,7 +110,7 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('17:00'),
|
||||
find.text('5:00 PM'),
|
||||
findsOneWidget,
|
||||
reason: 'Time of existing meal is filled in',
|
||||
);
|
||||
@@ -122,7 +121,6 @@ void main() {
|
||||
reason: 'Time of existing meal is filled in',
|
||||
);
|
||||
|
||||
await tester.enterText(find.byKey(const Key('field-time')), '12:34');
|
||||
await tester.enterText(find.byKey(const Key('field-name')), 'test meal');
|
||||
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
|
||||
|
||||
@@ -156,12 +154,11 @@ void main() {
|
||||
);
|
||||
|
||||
expect(
|
||||
find.text(timeToString(TimeOfDay.fromDateTime(clock.now()))!),
|
||||
find.text('1:01 AM'),
|
||||
findsOneWidget,
|
||||
reason: 'Current time is filled in',
|
||||
);
|
||||
|
||||
await tester.enterText(find.byKey(const Key('field-time')), '08:00');
|
||||
await tester.enterText(find.byKey(const Key('field-name')), 'test meal');
|
||||
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
|
||||
|
||||
|
||||
@@ -67,8 +67,8 @@ void main() {
|
||||
expect(find.widgetWithText(TextFormField, 'Existing notes'), findsOneWidget);
|
||||
final toggleButtons = tester.widget<ToggleButtons>(find.byType(ToggleButtons));
|
||||
expect(toggleButtons.isSelected, [true, false, false]); // Bad impression
|
||||
expect(find.widgetWithText(TextFormField, '10:00'), findsOneWidget);
|
||||
expect(find.widgetWithText(TextFormField, '11:00'), findsOneWidget);
|
||||
expect(find.widgetWithText(TextFormField, '10:00 AM'), findsOneWidget);
|
||||
expect(find.widgetWithText(TextFormField, '11:00 AM'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('saves a new session', (WidgetTester tester) async {
|
||||
|
||||
@@ -302,7 +302,7 @@ void main() {
|
||||
expect(find.byIcon(Icons.sentiment_neutral), findsOneWidget);
|
||||
expect(find.byIcon(Icons.sentiment_very_satisfied), findsOneWidget);
|
||||
expect(
|
||||
find.text('14:33'),
|
||||
find.text('2:33 PM'),
|
||||
findsNWidgets(2),
|
||||
reason: 'start and end time are the same',
|
||||
);
|
||||
|
||||
@@ -22,12 +22,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:wger/helpers/json.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/models/workouts/routine.dart';
|
||||
import 'package:wger/models/workouts/session.dart';
|
||||
import 'package:wger/providers/gym_state.dart';
|
||||
import 'package:wger/providers/workout_session_repository.dart';
|
||||
import 'package:wger/widgets/core/datetime_input.dart';
|
||||
import 'package:wger/widgets/routines/gym_mode/session_page.dart';
|
||||
|
||||
import '../../../test_data/routines.dart';
|
||||
@@ -98,8 +98,8 @@ void main() {
|
||||
await tester.pumpWidget(renderSessionPage());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('10:00'), findsOneWidget);
|
||||
expect(find.text('12:34'), findsOneWidget);
|
||||
expect(find.text('10:00 AM'), findsOneWidget);
|
||||
expect(find.text('12:34 PM'), findsOneWidget);
|
||||
expect(find.text('This is a note'), findsOneWidget);
|
||||
final toggleButtons = tester.widget<ToggleButtons>(find.byType(ToggleButtons));
|
||||
expect(toggleButtons.isSelected[2], isTrue);
|
||||
@@ -119,18 +119,17 @@ void main() {
|
||||
|
||||
final startTimeField = find.byKey(const ValueKey('time-start'));
|
||||
expect(startTimeField, findsOneWidget);
|
||||
expect(tester.widget<TextFormField>(startTimeField).controller!.text, '');
|
||||
expect(tester.widget<TimeInputWidget>(startTimeField).value, isNull);
|
||||
|
||||
final endTimeField = find.byKey(const ValueKey('time-end'));
|
||||
expect(endTimeField, findsOneWidget);
|
||||
expect(tester.widget<TextFormField>(endTimeField).controller!.text, '');
|
||||
expect(tester.widget<TimeInputWidget>(endTimeField).value, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('Test correct default data (no existing session)', (WidgetTester tester) async {
|
||||
// Arrange
|
||||
testRoutine.sessions = [];
|
||||
final timeNow = timeToString(TimeOfDay.now())!;
|
||||
notifier.state = notifier.state.copyWith(
|
||||
startTime: const TimeOfDay(hour: 13, minute: 35),
|
||||
);
|
||||
@@ -140,7 +139,8 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Assert
|
||||
expect(find.text('13:35'), findsOneWidget);
|
||||
final timeNow = TimeOfDay.now().format(tester.element(find.byType(TextFormField).first));
|
||||
expect(find.text('1:35 PM'), findsOneWidget);
|
||||
expect(find.text(timeNow), findsOneWidget);
|
||||
final toggleButtons = tester.widget<ToggleButtons>(find.byType(ToggleButtons));
|
||||
expect(toggleButtons.isSelected[1], isTrue);
|
||||
|
||||
@@ -17,20 +17,35 @@
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_riverpod/misc.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
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_repository.dart';
|
||||
import 'package:wger/widgets/weight/forms.dart';
|
||||
|
||||
import '../../test_data/body_weight.dart';
|
||||
import 'weight_form_test.mocks.dart';
|
||||
|
||||
@GenerateMocks([BodyWeightRepository])
|
||||
void main() {
|
||||
Widget createWeightForm({locale = 'en', weightEntry = WeightEntry}) {
|
||||
return MaterialApp(
|
||||
locale: Locale(locale),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(body: WeightForm(weightEntry)),
|
||||
Widget createWeightForm({
|
||||
locale = 'en',
|
||||
weightEntry = WeightEntry,
|
||||
List<Override> overrides = const [],
|
||||
}) {
|
||||
return ProviderScope(
|
||||
overrides: overrides,
|
||||
child: MaterialApp(
|
||||
locale: Locale(locale),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(body: WeightForm(weightEntry)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -91,4 +106,29 @@ void main() {
|
||||
await tester.pumpWidget(createWeightForm(weightEntry: null));
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
|
||||
testWidgets('Saving keeps an afternoon (PM) time intact', (WidgetTester tester) async {
|
||||
final mockRepo = MockBodyWeightRepository();
|
||||
when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value(<WeightEntry>[]));
|
||||
when(mockRepo.updateLocalDrift(any)).thenAnswer((_) async {});
|
||||
|
||||
await tester.pumpWidget(
|
||||
createWeightForm(
|
||||
weightEntry: testWeightEntry1,
|
||||
overrides: [bodyWeightRepositoryProvider.overrideWithValue(mockRepo)],
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The stored 15:30 renders as a PM time in a 12-hour locale
|
||||
expect(find.text('3:30 PM'), findsOneWidget);
|
||||
|
||||
// Save without changing anything
|
||||
await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final saved = verify(mockRepo.updateLocalDrift(captureAny)).captured.single as WeightEntry;
|
||||
expect(saved.date.hour, 15);
|
||||
expect(saved.date.minute, 30);
|
||||
});
|
||||
}
|
||||
|
||||
69
test/weight/weight_form_test.mocks.dart
Normal file
69
test/weight/weight_form_test.mocks.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
// Mocks generated by Mockito 5.4.6 from annotations
|
||||
// in wger/test/weight/weight_form_test.dart.
|
||||
// Do not manually edit this file.
|
||||
|
||||
// ignore_for_file: no_leading_underscores_for_library_prefixes
|
||||
import 'dart:async' as _i3;
|
||||
|
||||
import 'package:mockito/mockito.dart' as _i1;
|
||||
import 'package:wger/models/body_weight/weight_entry.dart' as _i4;
|
||||
import 'package:wger/providers/body_weight_repository.dart' as _i2;
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: avoid_redundant_argument_values
|
||||
// ignore_for_file: avoid_setters_without_getters
|
||||
// ignore_for_file: comment_references
|
||||
// ignore_for_file: deprecated_member_use
|
||||
// ignore_for_file: deprecated_member_use_from_same_package
|
||||
// ignore_for_file: implementation_imports
|
||||
// ignore_for_file: invalid_use_of_visible_for_testing_member
|
||||
// ignore_for_file: must_be_immutable
|
||||
// ignore_for_file: prefer_const_constructors
|
||||
// ignore_for_file: unnecessary_parenthesis
|
||||
// ignore_for_file: camel_case_types
|
||||
// ignore_for_file: subtype_of_sealed_class
|
||||
// ignore_for_file: invalid_use_of_internal_member
|
||||
|
||||
/// A class which mocks [BodyWeightRepository].
|
||||
///
|
||||
/// See the documentation for Mockito's code generation for more information.
|
||||
class MockBodyWeightRepository extends _i1.Mock implements _i2.BodyWeightRepository {
|
||||
MockBodyWeightRepository() {
|
||||
_i1.throwOnMissingStub(this);
|
||||
}
|
||||
|
||||
@override
|
||||
_i3.Stream<List<_i4.WeightEntry>> watchAllDrift() =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#watchAllDrift, []),
|
||||
returnValue: _i3.Stream<List<_i4.WeightEntry>>.empty(),
|
||||
)
|
||||
as _i3.Stream<List<_i4.WeightEntry>>);
|
||||
|
||||
@override
|
||||
_i3.Future<void> deleteLocalDrift(String? id) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#deleteLocalDrift, [id]),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
|
||||
@override
|
||||
_i3.Future<void> updateLocalDrift(_i4.WeightEntry? entry) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#updateLocalDrift, [entry]),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
|
||||
@override
|
||||
_i3.Future<void> addLocalDrift(_i4.WeightEntry? entry) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#addLocalDrift, [entry]),
|
||||
returnValue: _i3.Future<void>.value(),
|
||||
returnValueForMissingStub: _i3.Future<void>.value(),
|
||||
)
|
||||
as _i3.Future<void>);
|
||||
}
|
||||
Reference in New Issue
Block a user