// Health ▸ Body: tiles (weight + change, BMI, waist, body fat), the chart (weight / waist / BMI / // body fat over 3 months · 1 year · all), body fat by every formula, ratios + resting energy, the // measurements (tap = edit, + = add). The numbers are the web page's (body_model.dart). // Categories: tap a tile (the web page shows them on hover). import 'package:flutter/material.dart'; import '../app/sync_service.dart'; import '../app/theme.dart'; import '../widgets/line_chart.dart'; import 'body_model.dart'; import 'cycle_model.dart' show plus, today; import 'range.dart'; const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; String dm(DateTime d) => '${d.day} ${_mon[d.month - 1]}'; String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}'; String n1(double? v) => v == null ? '—' : v.toStringAsFixed(1); /// 115 not 115.0; 124.6 stays. String trim1(double? v) => v == null ? '—' : n1(v).replaceFirst(RegExp(r'\.0$'), ''); const _short = {'weight': 'weight', 'waist': 'waist', 'hip': 'hips', 'neck': 'neck', 'chest': 'chest', 'arm': 'arm', 'thigh': 'thigh', 'fat_scale': 'scale fat'}; /// A category word → its colour (healthy green, raised amber, high red, low blue). Color classColor(String? c) { if (c == null) return muted; if (RegExp(r'very high|obese|severe|vhigh|very low').hasMatch(c)) return bad; if (RegExp(r'^(healthy|normal|non-elevated|ok)').hasMatch(c)) return good; if (RegExp(r'^(low|underweight)').hasMatch(c)) return const Color(0xFF5CC8FF); return accent; } class BodyPage extends StatefulWidget { const BodyPage({super.key, required this.sync, required this.range}); final SyncService sync; final HealthRange range; @override State createState() => _BodyPageState(); } class _BodyPageState extends State { String chart = 'weight'; int shown = 5; @override Widget build(BuildContext context) => Scaffold( floatingActionButton: FloatingActionButton( backgroundColor: accent, foregroundColor: bg, tooltip: 'Add measurements', onPressed: () => _edit(BodyView(widget.sync.store, profileOf(widget.sync.store)), null), child: const Icon(Icons.add), ), body: ListenableBuilder( listenable: Listenable.merge([widget.sync, widget.range]), builder: (context, _) { final v = BodyView(widget.sync.store, profileOf(widget.sync.store)); if (v.rows.isEmpty) { return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted))); } return LayoutBuilder(builder: (context, box) { final wide = box.maxWidth >= 700; final left = [_tiles(v, wide), const SizedBox(height: 12), _chart(v)]; final right = [_fat(v), const SizedBox(height: 12), _ratios(v), const SizedBox(height: 12), _list(v)]; return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 88), children: [ if (wide) Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded(child: Column(children: left)), const SizedBox(width: 12), Expanded(child: Column(children: right)), ]) else ...[...left, const SizedBox(height: 12), ...right], ]); }); }, ), ); // ---- tiles Widget _tiles(BodyView v, bool wide) { final wc = v.change('weight'); final b = v.bmiNow; String from(String k) { final c = v.cur[k]; if (c == null) return ''; return c.day == v.now ? 'today' : c.stale ? 'old: ${dmy(c.day)}' : dm(c.day); } final tiles = [ _Tile('Weight', v.weight == null ? '—' : '${trim1(v.weight)} kg', wc == null ? from('weight') : '${wc.$1 >= 0 ? '+' : '−'}${wc.$1.abs().toStringAsFixed(1)} kg in ${wc.$3} days', null, () => _info('Weight', _weightInfo(v))), _Tile('BMI', b == null ? '—' : n1(b), bmiClass(b) ?? 'needs height + weight', bmiClass(b), () => _info('BMI', _bmiInfo(v))), _Tile('Waist', v.waist == null ? '—' : '${trim1(v.waist)} cm', waistClass(v.waist, v.p.sex) ?? from('waist'), waistClass(v.waist, v.p.sex), () => _info('Waist', _waistInfo(v))), _Tile('Body fat', v.fatMid == null ? '—' : '${n1(v.fatMid)} %', fatClass(v.fatMid, v.p.sex, v.age) ?? 'needs measurements', fatClass(v.fatMid, v.p.sex, v.age), () => _info('Body fat', _fatInfo(v))), ]; return GridView.count( crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9, children: tiles, ); } Widget _weightInfo(BodyView v) { final hw = healthyWeight(v.p.height); return Text(hw == null ? 'Set your height on the dashboard.' : 'Healthy weight for ${v.p.height} cm (BMI 18.5–24.9): ${hw.$1.toStringAsFixed(1)}–${hw.$2.toStringAsFixed(1)} kg.'); } Widget _bmiInfo(BodyView v) { final band = bmiAgeBand(v.age); return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('WHO classes (all adults): under 18.5 underweight · 18.5–25 normal · 25–30 overweight · 30+ obese (I 30–35, II 35–40, III 40+).'), const SizedBox(height: 10), const Text('Desirable BMI by age (NRC 1989):', style: TextStyle(color: muted)), for (final r in bmiAge) Text('${r.$1}–${r.$2 > 100 ? '+' : r.$2}: ${r.$3}–${r.$4}', style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)), const SizedBox(height: 8), const Text('BMI reads muscle as fat; the waist and body fat say more.', style: TextStyle(color: muted)), ]); } Widget _waistInfo(BodyView v) => Text(v.p.sex == female ? 'WHO (European women): under 80 cm healthy · 80–88 raised · 88+ high.' : 'WHO (European men): under 94 cm healthy · 94–102 raised · 102+ high.'); Widget _fatInfo(BodyView v) { final rows = fatRanges[v.p.sex == female ? female : 'male']!; final band = fatBand(v.p.sex, v.age); return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Healthy body fat by age (${v.p.sex}, Gallagher et al. 2000):', style: const TextStyle(color: muted)), for (final r in rows) Text('${r.$1}–${r.$2}: healthy ${r.$3.round()}–${r.$4.round()} % · high from ${r.$4.round()} · very high from ${r.$5.round()}', style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)), const SizedBox(height: 8), const Text('The middle (median) of every formula that has its measurements; they disagree by a few points.', style: TextStyle(color: muted)), ]); } void _info(String title, Widget body) => showModalBottomSheet( context: context, backgroundColor: card, builder: (_) => Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 28), child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), const SizedBox(height: 10), body, ]), ), ); // ---- chart Widget _chart(BodyView v) { final sr = v.series(); final from = widget.range.from(v.rows.first.day, v.now); final hw = healthyWeight(v.p.height); const fatColors = [Color(0xFFFFB33A), Color(0xFF5CC8FF), Color(0xFFC792EA), Color(0xFF7FD6A3)]; final (List s, String unit, (double, double)? band) = switch (chart) { 'waist' => ([Series('Waist', sr['waist']!, accent)], 'cm', null), 'bmi' => ([Series('BMI', sr['bmi']!, accent)], '', (18.5, 25.0)), 'fat' => ([for (var i = 0; i < fatFormulas.length; i++) Series(fatFormulas[i].$2, sr[fatFormulas[i].$1]!, fatColors[i])], '%', null), _ => ([Series('Weight', sr['weight']!, accent)], 'kg', hw), }; return Card( child: Padding( padding: const EdgeInsets.fromLTRB(12, 10, 12, 6), child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row(children: [ for (final (k, l) in [('weight', 'Weight'), ('waist', 'Waist'), ('bmi', 'BMI'), ('fat', 'Body fat')]) Padding(padding: const EdgeInsets.only(right: 6), child: ChoiceChip(label: Text(l), selected: chart == k, onSelected: (_) => setState(() => chart = k))), ]), ), const SizedBox(height: 8), LineChart(series: s, from: from, to: plus(v.now, 1), unit: unit, band: band, range: widget.range), if (chart == 'fat') Wrap(spacing: 10, children: [ for (var i = 0; i < fatFormulas.length; i++) Text('● ${fatFormulas[i].$2}', style: TextStyle(color: fatColors[i], fontSize: 12)), ]), ]), ), ); } // ---- body fat by formula Widget _fat(BodyView v) => _Card('Body fat', [ for (final f in v.fat) Tooltip( triggerMode: TooltipTriggerMode.tap, message: f.note, child: _Row(f.name, f.value != null ? '${n1(f.value)} %' : 'needs ${f.missing.map(_need).join(', ')}', f.value == null ? muted : classColor(fatClass(f.value, v.p.sex, v.age))), ), const Divider(color: card2), _Row('Middle of ${v.fat.where((f) => f.value != null).length}', v.fatMid == null ? '—' : '${n1(v.fatMid)} %${v.fatRange == null ? '' : ' (${n1(v.fatRange!.$1)}–${n1(v.fatRange!.$2)})'}', classColor(fatClass(v.fatMid, v.p.sex, v.age))), if (v.weight != null && v.fatMid != null) _Row('Fat · lean', '${(v.weight! * v.fatMid! / 100).toStringAsFixed(1)} kg · ${(v.weight! * (1 - v.fatMid! / 100)).toStringAsFixed(1)} kg', null), ]); static String _need(String k) => k == 'height' ? 'height' : k == 'fat_scale' ? 'a scale reading' : fields[k]!.$1.toLowerCase(); // ---- ratios + energy Widget _ratios(BodyView v) { final r1 = whtr(v.waist, v.p.height), r2 = whr(v.waist, v.hip); final m = bmrMifflin(v.weight, v.p.height, v.p.sex, v.age), k = bmrKatch(v.weight, v.fatMid); return _Card('Ratios & energy', [ _Row('Waist ÷ height', r1 == null ? '—' : '${r1.toStringAsFixed(2)} · ${whtrClass(r1)}', classColor(whtrClass(r1))), _Row('Waist ÷ hips', r2 == null ? '—' : '${r2.toStringAsFixed(2)} · ${whrClass(r2, v.p.sex)}', classColor(whrClass(r2, v.p.sex))), _Row('Resting energy', m == null ? '—' : '${m.round()} kcal/day${k == null ? '' : ' · ${k.round()} from lean mass'}', null), ]); } // ---- the measurements Widget _list(BodyView v) { final from = widget.range.from(v.rows.first.day, v.now); // the charts' period final rows = v.rows.reversed.where((r) => !r.day.isBefore(from)).toList(); return _Card('Measurements', [ if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), child: Text('Nothing measured in this period', style: TextStyle(color: muted))), for (final r in rows.take(shown)) InkWell( onTap: () => _edit(v, r), child: Padding( padding: const EdgeInsets.symmetric(vertical: 7), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(width: 92, child: Text(r.day.year == v.now.year ? dm(r.day) : dmy(r.day), style: const TextStyle(color: muted))), Expanded(child: Text([ for (final k in fields.keys) if (r[k] != null) '${_short[k]} ${trim1(r[k])}', if (r.note.isNotEmpty) '“${r.note}”', ].join(' · '))), ]), ), ), if (rows.length > shown) TextButton(onPressed: () => setState(() => shown += 5), child: Text('Show more (${rows.length - shown})')), ]); } Future _edit(BodyView v, Measure? m) => showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: card, builder: (_) => MeasureSheet(v: v, m: m, onSave: (d, vals, note, was) { final err = saveMeasure(widget.sync.store, d, vals, note, was: was); if (err == null) widget.sync.changed(); return err; }, onDelete: m == null ? null : () { saveMeasure(widget.sync.store, m.day, {}, ''); widget.sync.changed(); }), ); } class _Tile extends StatelessWidget { const _Tile(this.label, this.value, this.sub, this.cls, this.onTap); final String label, value, sub; final String? cls; final VoidCallback onTap; @override Widget build(BuildContext context) => Card( child: InkWell( borderRadius: BorderRadius.circular(12), onTap: onTap, child: Padding( padding: const EdgeInsets.all(12), child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)), Text(value, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)), Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: cls == null ? muted : classColor(cls), fontSize: 12.5)), ]), ), ), ); } class _Card extends StatelessWidget { const _Card(this.title, this.children); final String title; final List children; @override Widget build(BuildContext context) => Card( child: Padding( padding: const EdgeInsets.fromLTRB(14, 12, 14, 10), child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(height: 6), ...children, ]), ), ); } class _Row extends StatelessWidget { const _Row(this.k, this.v, this.color); final String k, v; final Color? color; @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row(children: [ Expanded(child: Text(k, style: const TextStyle(color: muted))), Flexible(child: Text(v, textAlign: TextAlign.right, style: TextStyle(color: color))), ]), ); } /// Add / edit a day's measurements: date, every field (placeholders = your last values), note. class MeasureSheet extends StatefulWidget { const MeasureSheet({super.key, required this.v, required this.m, required this.onSave, this.onDelete}); final BodyView v; final Measure? m; final String? Function(DateTime d, Map vals, String note, DateTime? was) onSave; final VoidCallback? onDelete; @override State createState() => _MeasureSheetState(); } class _MeasureSheetState extends State { late DateTime d = widget.m?.day ?? today(); late final ctl = { for (final k in fields.keys) k: TextEditingController(text: widget.m?[k] == null ? '' : trim1(widget.m![k])) }; late final note = TextEditingController(text: widget.m?.note ?? ''); String? error; bool armed = false; void _loadDay(DateTime nd) { // picking a day that already has measurements (when adding) loads them, like the web dialog final other = widget.v.rows.where((r) => r.day == nd).firstOrNull; setState(() { d = nd; if (widget.m == null && other != null) { for (final k in fields.keys) { ctl[k]!.text = other[k] == null ? '' : trim1(other[k]); } note.text = other.note; } }); } @override Widget build(BuildContext context) => Padding( padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom), child: SingleChildScrollView( child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row(children: [ Expanded(child: Text(widget.m == null ? 'Add measurements' : 'Edit measurements', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))), TextButton.icon( icon: const Icon(Icons.event, size: 18), label: Text(dmy(d)), onPressed: () async { final p = await showDatePicker(context: context, initialDate: d, firstDate: DateTime.utc(2000), lastDate: today()); if (p != null) _loadDay(DateTime.utc(p.year, p.month, p.day)); }, ), ]), const SizedBox(height: 4), GridView.count( crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), crossAxisSpacing: 12, childAspectRatio: 3.2, children: [ for (final e in fields.entries) TextField( controller: ctl[e.key], keyboardType: const TextInputType.numberWithOptions(decimal: true), textInputAction: TextInputAction.next, decoration: InputDecoration( labelText: e.key == 'fat_scale' ? 'Scale body fat' : e.value.$1, suffixText: e.value.$2, hintText: widget.v.cur[e.key] == null ? null : n1(widget.v.cur[e.key]!.v), ), ), ]), TextField(controller: note, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')), if (error != null) Padding(padding: const EdgeInsets.only(bottom: 8), child: Text(error!, style: const TextStyle(color: bad))), Row(children: [ if (widget.onDelete != null) TextButton( onPressed: () { if (!armed) return setState(() => armed = true); widget.onDelete!(); Navigator.pop(context); }, child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)), ), const Spacer(), FilledButton( onPressed: () { final vals = {}; for (final k in fields.keys) { final t = ctl[k]!.text.trim().replaceAll(',', '.'); if (t.isEmpty) { vals[k] = null; } else if (double.tryParse(t) == null) { return setState(() => error = '${fields[k]!.$1}: not a number.'); } else { vals[k] = double.parse(t); } } final err = widget.onSave(d, vals, note.text, widget.m?.day); if (err != null) return setState(() => error = err); Navigator.pop(context); }, child: const Text('Save'), ), ]), ]), ), ); }