diet-guard/app/lib/screens/body_screen.dart
Krzysztof kuhy Rudnicki 49144a2c49 Move the app to material_ui for Flutter 3.50
Flutter 3.50 deprecates package:flutter/material.dart; 73 deprecation
infos failed flutter analyze --fatal-infos, and four Dart pins were
behind (crdt_sync_flutter 0.8.2, flutter_local_notifications 23.0.2,
github_device_auth 0.5.0, sync_settings_ui 0.8.2). Those UI packages
now sit on material_ui, so the app has to as well or their widgets lose
MaterialLocalizations.

Imports swap one-for-one and dart fix re-sorted the directives; no
behaviour change. analyze is clean and all six test shards pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
2026-11-16 09:25:34 +01:00

248 lines
8.4 KiB
Dart

/// The Body screen: the goal sentence first, then weight (+ graph), BMI,
/// ideal weight, BMR, measured activity and steps, the week planner, the
/// profile (at the top instead while incomplete), and body fat last.
///
/// The phone half of the PC gate's Body tab (`_gatelock_body*.py`), reading
/// the same synced `body.json` (see `docs/DOCS-body.md`). **Informational
/// only**: nothing here writes the daily budget -- there is deliberately no
/// "apply" button.
library;
import 'dart:async';
import 'package:diet_guard_app/screens/body_screen_data.dart';
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/body_calc.dart';
import 'package:diet_guard_app/services/body_energy.dart';
import 'package:diet_guard_app/services/body_prefs.dart';
import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/health_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/activity_card.dart';
import 'package:diet_guard_app/widgets/body/body_section.dart';
import 'package:diet_guard_app/widgets/body/body_stats_cards.dart';
import 'package:diet_guard_app/widgets/body/body_tile_grid.dart';
import 'package:diet_guard_app/widgets/body/goal_card.dart';
import 'package:diet_guard_app/widgets/body/profile_card.dart';
import 'package:diet_guard_app/widgets/body/week_plan_card.dart';
import 'package:diet_guard_app/widgets/body/weight_card.dart';
import 'package:material_ui/material_ui.dart';
export 'package:diet_guard_app/screens/body_screen_data.dart';
/// The Body screen.
class BodyScreen extends StatefulWidget {
/// Creates the screen.
const BodyScreen({super.key});
@override
State<BodyScreen> createState() => _BodyScreenState();
}
class _BodyScreenState extends State<BodyScreen> {
Map<String, double> _logged = const {};
/// Decided once, when the screen opens: a complete profile sits at the
/// bottom, an incomplete one at the top. Re-deciding on every build would
/// yank the card away mid-edit the moment the last field is saved; it
/// moves the next time the screen is entered.
late final bool _profileAtTop = !BodyService.instance.profileComplete;
/// Whether the Health Connect button shows: supported and not yet granted.
///
/// A notifier, not a bool: the Activity sheet stays open while the
/// permission is granted, and its button must disappear and its numbers
/// refresh without reopening the sheet.
final ValueNotifier<bool> _canConnectSteps = ValueNotifier(false);
@override
void dispose() {
_canConnectSteps.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
unawaited(_loadLog());
unawaited(_loadSteps());
}
/// Refreshes steps (only when already permitted -- never prompts) and
/// decides whether to offer the connect button.
Future<void> _loadSteps() async {
final source = stepsSource;
if (!source.supported) return;
final granted = await source.hasPermission().catchError((_) => false);
if (granted) await refreshSteps();
if (!mounted) return;
_canConnectSteps.value = !granted;
setState(() {});
}
Future<void> _connectSteps() async {
final granted = await stepsSource.requestPermission().catchError(
(_) => false,
);
if (granted) await refreshSteps();
if (!mounted) return;
_canConnectSteps.value = !granted;
setState(() {});
}
Future<void> _loadLog() async {
final log = await LogStorageService.instance.readLog();
if (!mounted) return;
setState(() => _logged = kcalByDay(log));
}
/// Any profile/weight write changes every derived card; the cards read
/// [BodyService] in `build`, so a rebuild is all they need.
void _onChanged() => setState(() {});
@override
Widget build(BuildContext context) {
final body = BodyService.instance;
final today = DateTime.now();
final bio = currentBiometrics(body, today);
final (exercise, _, _) = bodyExercise(body, bio, today);
final tiles = _tiles(body, bio, exercise);
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: BodyTileGrid(tiles: tiles),
),
),
),
);
}
/// The Activity card from the live service state.
Widget _activityCard({required bool canConnect}) {
final body = BodyService.instance;
final (exercise, stepsKcal, window) = bodyExercise(
body,
currentBiometrics(body, DateTime.now()),
DateTime.now(),
);
return ActivityCard(
sessions: body.sessions,
weightKg: body.latestWeight?.$2,
exercise: exercise,
steps: stepsByDay(body),
stepsKcal: stepsKcal,
window: window,
onConnectSteps: canConnect ? _connectSteps : null,
);
}
/// Every section as a tile: the profile first while it is incomplete, last
/// otherwise (decided once, see [_profileAtTop]).
List<BodyTileSpec> _tiles(
BodyService body,
Biometrics? bio,
Map<String, double>? exercise,
) {
final weight = body.latestWeight?.$2;
final bodyFat = body.latestBodyFat?.$2;
final age = bodyAgeText(body, DateTime.now());
final profile = BodyTileSpec(
semanticLabel: 'Profile',
icon: Icons.person,
value: age,
valueIcon: age == null ? null : Icons.cake,
builder: (_) => ProfileCard(onSaved: _onChanged),
);
final goal = bio == null
? null
: goalTarget(
savedGoal(body),
tableBmr(bio, bodyFat).value!,
tableBmr(bio, bodyFat).name,
exercise,
).kcal;
return [
if (_profileAtTop) profile,
BodyTileSpec(
semanticLabel: 'Daily calorie target',
icon: Icons.flag,
value: goal == null ? null : '$goal',
valueIcon: goal == null ? null : MacroKind.kcal.icon,
builder: (_) => bio == null
? BodySection(
semanticLabel: 'Daily calorie target',
children: [
Row(
children: [
for (final icon in bodyMissingIcons(body))
StatusCue(
kind: CueKind.warn,
icon: icon,
semanticLabel: bodyMissingNote(body),
),
],
),
],
)
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
),
BodyTileSpec(
semanticLabel: 'Weight',
icon: Icons.monitor_weight,
value: weight == null ? null : formatKg(weight),
builder: (_) => WeightCard(onChanged: _onChanged),
),
if (bio != null) ...[
BodyTileSpec(
semanticLabel: 'BMI',
icon: Icons.accessibility_new,
value: oneDecimal(bmiReport(bio).bmi),
builder: (_) => BmiCard(bio: bio),
),
BodyTileSpec(
semanticLabel: 'Ideal weight',
icon: Icons.balance,
builder: (_) => IdealWeightCard(bio: bio),
),
BodyTileSpec(
semanticLabel: 'Resting metabolism (BMR)',
icon: Icons.bedtime,
value: whole(tableBmr(bio, bodyFat).value!),
valueIcon: MacroKind.kcal.icon,
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
),
],
BodyTileSpec(
semanticLabel: 'Activity',
icon: Icons.directions_run,
builder: (_) => ValueListenableBuilder<bool>(
valueListenable: _canConnectSteps,
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
),
),
BodyTileSpec(
semanticLabel: 'Week planner',
icon: Icons.calendar_view_week,
builder: (_) => WeekPlanCard(
defaultTarget: AppSettingsService.dailyKcalGoal,
logged: _logged,
),
),
if (!_profileAtTop) profile,
BodyTileSpec(
semanticLabel: 'Body fat',
icon: Icons.percent,
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
builder: (_) => BodyFatCard(onChanged: _onChanged),
),
];
}
}