Let the phone set the eating window and meal count

The first edit surface, landing after the sync layer so a schedule set here
reaches the PC rather than leaving the two devices deriving different slots.

Three dropdowns -- first meal, last meal, meals per day -- and a live preview
of the checkpoints they derive. Setting 08:00, 20:00 and 5 shows
08:00 · 11:00 · 14:00 · 17:00 · 20:00, which is asserted in the screen test
rather than only in the model's.

Dropdowns rather than showTimePicker: that returns a TimeOfDay with minutes,
and slots are whole hours on both devices by design. They also make the
invalid states unrepresentable instead of validated -- "last meal" offers only
hours after "first", and "meals per day" only counts the window has whole
hours for. MealSchedule.normalized() still clamps, but that is the defence
against corrupt synced data, not the input contract.

Saving re-runs the due-slot check, because reminder ids are slot hours: a
schedule change orphans the ids it no longer contains, and waiting for the
next background tick would leave a stale nag on screen for up to 15 minutes.

The UI is a `part` mixin like settings_kcal_goal.dart -- settings_screen.dart
was at 238 of the 250-line cap and is now at 247.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
This commit is contained in:
Krzysztof Rudnicki 2026-08-16 14:56:12 +02:00
parent 24dbffc432
commit da8822006f
4 changed files with 197 additions and 3 deletions

View File

@ -0,0 +1,147 @@
// The meal-schedule editor: first meal, last meal, how many meals, and a
// live preview of the checkpoint times they derive.
//
// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part`
// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's
// private state and calls `setState`.
part of 'settings_screen.dart';
mixin _SettingsMealSchedule on State<SettingsScreen> {
MealSchedule _schedule = kDefaultSchedule;
void _loadSchedule() {
_schedule = MealScheduleService.current;
}
/// The meal counts selectable for the current window.
///
/// Capped at the number of whole hours the window holds, so the count
/// dropdown can never offer a value that would round two meals onto the
/// same hour. Invalid states are made unrepresentable here rather than
/// validated after the fact -- `MealSchedule.normalized` still clamps, but
/// that is the defence against corrupt synced data, not the input contract.
List<int> get _selectableCounts {
final span = _schedule.last - _schedule.first;
final maxCount = span + 1 < kMaxMealCount ? span + 1 : kMaxMealCount;
return [for (var n = kMinMealCount; n <= maxCount; n++) n];
}
Future<void> _applySchedule(MealSchedule next) async {
final normalized = next.normalized();
setState(() => _schedule = normalized);
if (!MealScheduleService.isInitialized) return;
await MealScheduleService.instance.recordChange(normalized);
// The reminder ids are slot hours, so a schedule change orphans the ones
// it no longer contains. Re-running the check cancels them immediately
// rather than leaving a stale nag until the next background tick.
await checkAndNotify(pullWhenDue: false);
}
/// Dropdowns rather than a time picker: `showTimePicker` returns minutes,
/// and slots are whole hours on both devices by design.
Widget _hourDropdown({
required String label,
required int value,
required List<int> hours,
required ValueChanged<int> onChanged,
}) => ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: InputDecoration(labelText: label),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: value,
isDense: true,
isExpanded: true,
items: [
for (final hour in hours)
DropdownMenuItem(value: hour, child: Text(slotLabel(hour))),
],
onChanged: (hour) => hour == null ? null : onChanged(hour),
),
),
),
);
List<Widget> _mealScheduleSection(BuildContext context) {
final theme = Theme.of(context);
final counts = _selectableCounts;
return [
Text('Meal times', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
'Checkpoints are spread evenly between your first and last meal.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
_hourDropdown(
label: 'First meal',
value: _schedule.first,
// Leaves at least one hour of window, so `last` always has a value
// strictly after `first` to offer.
hours: [for (var h = kFirstHour; h < kLastHour; h++) h],
onChanged: (hour) => unawaited(
_applySchedule(
MealSchedule(
first: hour,
last: _schedule.last,
count: _schedule.count,
),
),
),
),
const SizedBox(height: 12),
_hourDropdown(
label: 'Last meal',
value: _schedule.last,
hours: [for (var h = _schedule.first + 1; h <= kLastHour; h++) h],
onChanged: (hour) => unawaited(
_applySchedule(
MealSchedule(
first: _schedule.first,
last: hour,
count: _schedule.count,
),
),
),
),
const SizedBox(height: 12),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: InputDecorator(
decoration: const InputDecoration(labelText: 'Meals per day'),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
value: counts.contains(_schedule.count)
? _schedule.count
: counts.last,
isDense: true,
isExpanded: true,
items: [
for (final count in counts)
DropdownMenuItem(value: count, child: Text('$count')),
],
onChanged: (count) => count == null
? null
: unawaited(
_applySchedule(
MealSchedule(
first: _schedule.first,
last: _schedule.last,
count: count,
),
),
),
),
),
),
),
const SizedBox(height: 12),
Text(
_schedule.slots().map(slotLabel).join(' · '),
style: theme.textTheme.bodyMedium,
),
];
}
}

View File

@ -11,11 +11,15 @@ library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/due_slot_check.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@ -25,6 +29,7 @@ import 'package:permission_handler/permission_handler.dart';
import 'package:sync_settings_ui/sync_settings_ui.dart';
part 'settings_kcal_goal.dart';
part 'settings_meal_schedule.dart';
/// Screen for app-specific settings and links to sync configuration.
class SettingsScreen extends StatefulWidget {
@ -91,13 +96,14 @@ class SettingsScreen extends StatefulWidget {
}
class _SettingsScreenState extends State<SettingsScreen>
with _SettingsKcalGoal {
with _SettingsKcalGoal, _SettingsMealSchedule {
final _kcalGoalController = TextEditingController();
@override
void initState() {
super.initState();
_kcalGoalController.text = AppSettingsService.dailyKcalGoal.toString();
_loadSchedule();
}
@override
@ -177,6 +183,10 @@ class _SettingsScreenState extends State<SettingsScreen>
),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
..._mealScheduleSection(context),
const SizedBox(height: 24),
const Divider(),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Sync settings'),

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.34+1
version: 1.0.35+1
environment:
sdk: ^3.12.2

View File

@ -1,6 +1,7 @@
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/settings_screen.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
@ -8,6 +9,7 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler/permission_handler.dart';
@ -16,7 +18,6 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../fake_secure_storage.dart';
void main() {
late Directory tempDir;
setUp(() async {
@ -27,6 +28,7 @@ void main() {
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
await MealScheduleService.initForTesting(FileDocumentStore(tempDir));
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
});
@ -36,6 +38,7 @@ void main() {
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
MealScheduleService.resetForTesting();
await tempDir.delete(recursive: true);
});
@ -64,6 +67,40 @@ void main() {
expect(find.widgetWithText(TextField, '1800'), findsOneWidget);
});
});
testWidgets('shows the derived meal times for the stored schedule', (
tester,
) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);
// The default schedule still derives the hours that used to be
// hardcoded, so an existing install sees no change.
expect(
find.text('08:00 · 12:00 · 16:00 · 20:00'),
findsOneWidget,
);
expect(find.text('First meal'), findsOneWidget);
expect(find.text('Last meal'), findsOneWidget);
expect(find.text('Meals per day'), findsOneWidget);
});
});
testWidgets('reflects a five-meal schedule as the user\'s example', (
tester,
) async {
await tester.runAsync(() async {
await MealScheduleService.instance.recordChange(
const MealSchedule(first: 8, last: 20, count: 5),
);
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester);
expect(
find.text('08:00 · 11:00 · 14:00 · 17:00 · 20:00'),
findsOneWidget,
);
});
});
testWidgets('typing a kcal goal debounces the save', (tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));