Skip to content

Offline gym log for Android. No account, no ads, no internet.

Optional iron and potassium, and open a shared food JSON in the food editor

InlitXf26095d4caed
diff --git a/lib/app/app_shell.dart b/lib/app/app_shell.dart
index 073e62f..b7bd0ec 100644
--- a/lib/app/app_shell.dart
+++ b/lib/app/app_shell.dart
@@ -41,6 +41,7 @@ import '../services/auto_backup.dart';
import '../services/device_kind.dart';
import '../services/health_steps.dart';
import '../services/incoming_share.dart';
+import '../services/meal_ai.dart';
import '../services/nutrition_widgets.dart';
import '../services/local_store.dart';
import '../services/server/server_link.dart';
@@ -145,8 +146,18 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Single
}
void _openFromWidget(String route) {
- if (route == 'nfc/today') {
- if (mounted) openTodayFromTag(context);
+ if (route == 'nfc/today' || route == 'today') {
+ if (mounted) openTodayFromTag(context, tag: route != 'today');
+ return;
+ }
+ if (route == 'pass') {
+ if (!mounted || !fit.onboarded) return;
+ final pass = fit.quickPass;
+ if (pass == null) {
+ if (!fit.isSessionActive) fit.goGymPasses();
+ } else {
+ showGymPass(context, pass);
+ }
return;
}
if (!mounted || !fit.onboarded || fit.isSessionActive) return;
@@ -186,6 +197,13 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Single
_incoming = null;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
+ final food = text.contains(kFoodAiTag) ? parseFoodAi(text) : null;
+ if (food != null) {
+ fit.setNutritionBeta(true);
+ if (fit.route != 'nutrition') fit.goNutrition();
+ showFoodEditor(context, pick: food);
+ return;
+ }
if (fit.isMealPlanText(text)) {
final n = fit.importMealPlans(text);
if (n > 0) {
@@ -1263,7 +1281,7 @@ class _Sidebar extends StatelessWidget {
];
String _label(String id) => switch (id) {
- 'home' => titleCase(t.home),
+ 'home' => sentenceCase(t.home),
'progress' => titleCase(t.progress),
'exercises' => titleCase(t.exercises),
'settings' => sentenceCase(t.profile),
diff --git a/lib/models/nutrition.dart b/lib/models/nutrition.dart
index 1285f09..68db1b6 100644
--- a/lib/models/nutrition.dart
+++ b/lib/models/nutrition.dart
@@ -64,6 +64,8 @@ class Macros {
this.trans = 0,
this.mono = 0,
this.poly = 0,
+ this.iron = 0,
+ this.potassium = 0,
this.aminoProtein = 0,
this.amino = const [],
});
@@ -81,6 +83,8 @@ class Macros {
final double trans;
final double mono;
final double poly;
+ final double iron;
+ final double potassium;
final double aminoProtein;
final List<double> amino;
@@ -106,6 +110,8 @@ class Macros {
trans: trans + o.trans,
mono: mono + o.mono,
poly: poly + o.poly,
+ iron: iron + o.iron,
+ potassium: potassium + o.potassium,
aminoProtein: aminoProtein + o.aminoProtein,
amino: _addAmino(amino, o.amino),
);
@@ -124,6 +130,8 @@ class Macros {
trans: trans * k,
mono: mono * k,
poly: poly * k,
+ iron: iron * k,
+ potassium: potassium * k,
aminoProtein: aminoProtein * k,
amino: [for (final a in amino) a * k],
);
@@ -134,6 +142,8 @@ class Macros {
bool get hasFatTypes => sat > 0 || trans > 0 || mono > 0 || poly > 0;
+ bool get hasMinerals => iron > 0 || potassium > 0;
+
double get plant => (protein - animal).clamp(0, double.infinity).toDouble();
List<double> get aminoScores => aminoProtein <= 0 || amino.length != Amino.values.length
@@ -169,6 +179,8 @@ class Macros {
if (trans > 0) 'tf': trans,
if (mono > 0) 'mu': mono,
if (poly > 0) 'po': poly,
+ if (iron > 0) 'fe': iron,
+ if (potassium > 0) 'ka': potassium,
if (aminoProtein > 0 && amino.length == Amino.values.length) ...{
'ap': aminoProtein,
'aa': [for (final a in amino) (a * 1000).round() / 1000],
@@ -192,6 +204,8 @@ class Macros {
trans: _num(j?['tf']),
mono: _num(j?['mu']),
poly: _num(j?['po']),
+ iron: _num(j?['fe']),
+ potassium: _num(j?['ka']),
aminoProtein: ok ? _num(j?['ap']) : 0,
amino: ok ? aa : const [],
);
@@ -646,6 +660,8 @@ class NutritionGoals {
this.fiber = 30,
this.sugar = 50,
this.sodium = 2300,
+ this.iron = 0,
+ this.potassium = 0,
});
final int kcal;
@@ -657,6 +673,8 @@ class NutritionGoals {
final int fiber;
final int sugar;
final int sodium;
+ final int iron;
+ final int potassium;
int get satLimit => (kcal * 0.1 / 9).round();
@@ -670,6 +688,8 @@ class NutritionGoals {
int? fiber,
int? sugar,
int? sodium,
+ int? iron,
+ int? potassium,
}) =>
NutritionGoals(
kcal: kcal ?? this.kcal,
@@ -681,10 +701,23 @@ class NutritionGoals {
fiber: fiber ?? this.fiber,
sugar: sugar ?? this.sugar,
sodium: sodium ?? this.sodium,
+ iron: iron ?? this.iron,
+ potassium: potassium ?? this.potassium,
);
- Map<String, dynamic> toJson() =>
- {'k': kcal, 'p': protein, 'c': carbs, 'f': fat, 'w': waterMl, 'g': glassMl, 'fi': fiber, 'su': sugar, 'na': sodium};
+ Map<String, dynamic> toJson() => {
+ 'k': kcal,
+ 'p': protein,
+ 'c': carbs,
+ 'f': fat,
+ 'w': waterMl,
+ 'g': glassMl,
+ 'fi': fiber,
+ 'su': sugar,
+ 'na': sodium,
+ if (iron > 0) 'fe': iron,
+ if (potassium > 0) 'ka': potassium,
+ };
factory NutritionGoals.fromJson(Map<String, dynamic>? j) {
const d = NutritionGoals();
@@ -703,6 +736,8 @@ class NutritionGoals {
fiber: read('fi', d.fiber, 200),
sugar: read('su', d.sugar, 500),
sodium: read('na', d.sodium, 20000),
+ iron: read('fe', 0, 200),
+ potassium: read('ka', 0, 20000),
);
}
}
@@ -807,6 +842,7 @@ enum Tracker {
quality,
fats,
sugarSodium,
+ minerals,
water,
shake,
supplements,
@@ -824,5 +860,6 @@ const kTrackersOffByDefault = {
Tracker.quality,
Tracker.fats,
Tracker.sugarSodium,
+ Tracker.minerals,
Tracker.fasting,
};
diff --git a/lib/screens/nutrition/cards.dart b/lib/screens/nutrition/cards.dart
index 53c7245..319bbe1 100644
--- a/lib/screens/nutrition/cards.dart
+++ b/lib/screens/nutrition/cards.dart
@@ -106,6 +106,8 @@ String _extrasLine(Macros m) => [
if (m.sugar > 0) '${t.sugarLabel} ${_g(m.sugar)} g',
if (m.sodium > 0) '${t.sodiumLabel} ${m.sodium.round()} mg',
if (m.chol > 0) '${t.cholesterolLabel} ${m.chol.round()} mg',
+ if (fit.trackerOn(Tracker.minerals) && m.iron > 0) '${t.ironLabel} ${fmt((m.iron * 10).round() / 10)} mg',
+ if (fit.trackerOn(Tracker.minerals) && m.potassium > 0) '${t.potassiumLabel} ${m.potassium.round()} mg',
].join(' · ');
class _RingCard extends StatelessWidget {
@@ -116,8 +118,10 @@ class _RingCard extends StatelessWidget {
required this.value,
required this.sub,
required this.pct,
+ this.unit = 'g',
});
+ final String unit;
final IconData icon;
final Color color;
final String label;
@@ -153,7 +157,7 @@ class _RingCard extends StatelessWidget {
textBaseline: TextBaseline.alphabetic,
children: [
RollingText(value, style: AppTheme.f(21, weight: FontWeight.w800, color: gc.text, height: 1.05)),
- Text(' g', style: AppTheme.f(12, weight: FontWeight.w700, color: gc.textSecondary)),
+ Text(' $unit', style: AppTheme.f(12, weight: FontWeight.w700, color: gc.textSecondary)),
],
)),
),
@@ -212,8 +216,28 @@ class _DetailGrid extends StatelessWidget {
pct: total.sodium / goals.sodium,
),
],
+ if (fit.trackerOn(Tracker.minerals)) ...[
+ _RingCard(
+ icon: PhosphorIconsFill.drop,
+ color: gc.danger,
+ label: t.ironLabel,
+ value: fmt((total.iron * 10).round() / 10),
+ sub: '/ ${fit.ironGoal(goals)} mg',
+ pct: total.iron / fit.ironGoal(goals),
+ unit: 'mg',
+ ),
+ _RingCard(
+ icon: PhosphorIconsFill.lightning,
+ color: gc.sage,
+ label: t.potassiumLabel,
+ value: fmt((total.potassium / 100).round() / 10),
+ sub: '/ ${fmt(fit.potassiumGoal(goals) / 1000)} g',
+ pct: total.potassium / fit.potassiumGoal(goals),
+ ),
+ ],
];
if (cards.isEmpty) return const SizedBox.shrink();
+ final cover = fit.trackerOn(Tracker.minerals) ? fit.mineralsCoverage(day) : null;
const perRow = 2;
return Column(children: [
for (var i = 0; i < cards.length; i += perRow) ...[
@@ -232,6 +256,12 @@ class _DetailGrid extends StatelessWidget {
]),
),
],
+ if (cover != null && cover.total > 0 && cover.known < cover.total) ...[
+ const SizedBox(height: 8),
+ Text(t.mineralsCoverage(cover.known, cover.total),
+ textAlign: TextAlign.center,
+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textTertiary, height: 1.35)),
+ ],
]);
}
}
diff --git a/lib/screens/nutrition/food.dart b/lib/screens/nutrition/food.dart
index 9630dfd..bc9e861 100644
--- a/lib/screens/nutrition/food.dart
+++ b/lib/screens/nutrition/food.dart
@@ -947,6 +947,8 @@ class _ValueRows extends StatelessWidget {
if (per.sugar > 0) row(t.sugarLabel, '${_g(per.sugar)} g', gc.warn),
if (per.sodium > 0) row(t.sodiumLabel, '${per.sodium.round()} mg', gc.info),
if (per.chol > 0) row(t.cholesterolLabel, '${per.chol.round()} mg', gc.textSecondary),
+ if (per.iron > 0) row(t.ironLabel, '${fmt((per.iron * 10).round() / 10)} mg', gc.danger),
+ if (per.potassium > 0) row(t.potassiumLabel, '${per.potassium.round()} mg', gc.sage),
]),
);
}
@@ -1455,6 +1457,8 @@ class _EntryValuesSheetState extends State<_EntryValuesSheet> {
sugar: old.sugar,
sodium: old.sodium,
chol: old.chol,
+ iron: old.iron,
+ potassium: old.potassium,
animal: old.protein <= 0 ? 0 : old.animal / old.protein * m.protein,
sat: old.sat,
trans: old.trans,
@@ -1600,6 +1604,8 @@ Macros _macrosOf(
TextEditingController? trans,
TextEditingController? mono,
TextEditingController? poly,
+ TextEditingController? iron,
+ TextEditingController? potassium,
}) {
final protein = _read(p), carbs = _read(c), fat = _read(f);
var kcal = fit.kcalFromShown(_read(k));
@@ -1617,6 +1623,8 @@ Macros _macrosOf(
trans: trans == null ? 0 : _read(trans),
mono: mono == null ? 0 : _read(mono),
poly: poly == null ? 0 : _read(poly),
+ iron: iron == null ? 0 : _read(iron),
+ potassium: potassium == null ? 0 : _read(potassium),
);
}
@@ -1755,8 +1763,10 @@ Future<FoodItem?> showFoodEditor(
Meal? meal,
bool asShake = false,
String name = '',
+ AiFoodPick? pick,
}) =>
- _sheet<FoodItem?>(context, (_) => _FoodEditor(food: food, from: from, meal: meal, asShake: asShake, name: name));
+ _sheet<FoodItem?>(
+ context, (_) => _FoodEditor(food: food, from: from, meal: meal, asShake: asShake, name: name, pick: pick));
class _PhotoChoice extends StatelessWidget {
const _PhotoChoice({
@@ -1807,13 +1817,14 @@ class _PhotoChoice extends StatelessWidget {
}
class _FoodEditor extends StatefulWidget {
- const _FoodEditor({this.food, this.from, this.meal, this.asShake = false, this.name = ''});
+ const _FoodEditor({this.food, this.from, this.meal, this.asShake = false, this.name = '', this.pick});
final FoodItem? food;
final FoodItem? from;
final Meal? meal;
final bool asShake;
final String name;
+ final AiFoodPick? pick;
@override
State<_FoodEditor> createState() => _FoodEditorState();
@@ -1953,7 +1964,12 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
late final _trans = TextEditingController(text: _seed(_base?.macros.trans ?? 0));
late final _mono = TextEditingController(text: _seed(_base?.macros.mono ?? 0));
late final _poly = TextEditingController(text: _seed(_base?.macros.poly ?? 0));
- late bool _extras = (_base?.macros.hasExtras ?? false) || (_base?.macros.hasFatTypes ?? false);
+ late final _fe = TextEditingController(text: _seed(_base?.macros.iron ?? 0));
+ late final _ka = TextEditingController(text: _seed(_base?.macros.potassium ?? 0));
+ late final bool _minerals = fit.trackerOn(Tracker.minerals) || (_base?.macros.hasMinerals ?? false);
+ late bool _extras = (_base?.macros.hasExtras ?? false) ||
+ (_base?.macros.hasFatTypes ?? false) ||
+ (_base?.macros.hasMinerals ?? false);
late bool _shake = widget.asShake || (widget.food != null && fit.isShakeFood(widget.food!.id));
late int _water = _base?.water ?? 0;
late double _animalShare = _shareOf(_base?.macros);
@@ -1973,9 +1989,16 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
bool _owned(String? photo) =>
photo != null && photo.isNotEmpty && !isAssetPhoto(photo) && photo != widget.food?.photo;
+ @override
+ void initState() {
+ super.initState();
+ final pick = widget.pick;
+ if (pick != null) _take(pick);
+ }
+
@override
void dispose() {
- for (final c in [_name, _serving, _grams, _kcal, _p, _c, _f, _fi, _su, _na, _chol, _sat, _trans, _mono, _poly]) {
+ for (final c in [_name, _serving, _grams, _kcal, _p, _c, _f, _fi, _su, _na, _chol, _sat, _trans, _mono, _poly, _fe, _ka]) {
c.dispose();
}
_dropDrafts();
@@ -1991,7 +2014,16 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
var grams = (_read(_grams) * _k).clamp(0, 5000).toDouble();
if (_per100 && grams <= 0) grams = 100;
final typed = _macrosOf(_kcal, _p, _c, _f,
- fiber: _fi, sugar: _su, sodium: _na, chol: _chol, sat: _sat, trans: _trans, mono: _mono, poly: _poly);
+ fiber: _fi,
+ sugar: _su,
+ sodium: _na,
+ chol: _chol,
+ sat: _sat,
+ trans: _trans,
+ mono: _mono,
+ poly: _poly,
+ iron: _fe,
+ potassium: _ka);
final saved = fit.saveFood(
id: widget.food?.id,
name: name,
@@ -2019,41 +2051,45 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
Future<void> _fromAi() async {
final pick = await showFoodAiSheet(context);
if (pick == null || !mounted) return;
- final f = pick.food;
- String v(double? x) => _seed(x ?? 0);
- setState(() {
- _liquid = pick.liquid;
- if (f.name.isNotEmpty) _name.text = f.name;
- if (pick.serving.isNotEmpty) _serving.text = pick.serving;
- final g = f.grams;
- _grams.text = g == null || g <= 0 ? '' : _seed(g / _k);
- _per100 = f.per100 || g == null;
- _kcal.text = f.kcal == null ? '' : _seed(fit.energyOf(f.kcal!).toDouble());
- _p.text = v(f.protein);
- _c.text = v(f.carbs);
- _f.text = v(f.fat);
- _fi.text = v(f.fiber);
- _su.text = v(f.sugar);
- _na.text = v(f.sodium);
- _chol.text = v(f.chol);
- _sat.text = v(f.sat);
- _trans.text = v(f.trans);
- _mono.text = v(f.mono);
- _poly.text = v(f.poly);
- final extra = [f.fiber, f.sugar, f.sodium, f.chol, f.sat, f.trans, f.mono, f.poly];
- if (extra.any((x) => (x ?? 0) > 0)) _extras = true;
- });
+ setState(() => _take(pick));
showNotchToast(context, t.foodAiFilled,
subtitle: t.foodAiFilledHint, icon: PhosphorIconsFill.checkCircle, accent: context.gc.sage);
}
+ void _take(AiFoodPick pick) {
+ final f = pick.food;
+ String v(double? x) => _seed(x ?? 0);
+ _liquid = pick.liquid;
+ if (f.name.isNotEmpty) _name.text = f.name;
+ if (pick.serving.isNotEmpty) _serving.text = pick.serving;
+ final g = f.grams;
+ _grams.text = g == null || g <= 0 ? '' : _seed(g / _k);
+ _per100 = f.per100 || g == null;
+ _kcal.text = f.kcal == null ? '' : _seed(fit.energyOf(f.kcal!).toDouble());
+ _p.text = v(f.protein);
+ _c.text = v(f.carbs);
+ _f.text = v(f.fat);
+ _fi.text = v(f.fiber);
+ _su.text = v(f.sugar);
+ _na.text = v(f.sodium);
+ _chol.text = v(f.chol);
+ _sat.text = v(f.sat);
+ _trans.text = v(f.trans);
+ _mono.text = v(f.mono);
+ _poly.text = v(f.poly);
+ _fe.text = v(f.iron);
+ _ka.text = v(f.potassium);
+ final extra = [f.fiber, f.sugar, f.sodium, f.chol, f.sat, f.trans, f.mono, f.poly, f.iron, f.potassium];
+ if (extra.any((x) => (x ?? 0) > 0)) _extras = true;
+ }
+
void _setPer100(bool on) {
if (on == _per100) return;
HapticFeedback.selectionClick();
final grams = _read(_grams) * _k;
if (grams > 0) {
final k = on ? 100 / grams : grams / 100;
- for (final c in [_kcal, _p, _c, _f, _fi, _su, _na, _chol, _sat, _trans, _mono, _poly]) {
+ for (final c in [_kcal, _p, _c, _f, _fi, _su, _na, _chol, _sat, _trans, _mono, _poly, _fe, _ka]) {
final v = _read(c);
if (v > 0) c.text = _seed(v * k);
}
@@ -2136,6 +2172,8 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
sugar: m.sugar,
sodium: m.sodium,
chol: m.chol,
+ iron: m.iron,
+ potassium: m.potassium,
animal: m.protein * _animalShare,
sat: m.sat,
trans: m.trans,
@@ -2159,6 +2197,8 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
sugar: m.sugar,
sodium: m.sodium,
chol: m.chol,
+ iron: m.iron,
+ potassium: m.potassium,
animal: old.animal * k,
sat: m.sat,
trans: m.trans,
@@ -2312,7 +2352,17 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
label: t.cholesterolLabel.toUpperCase(), controller: _chol, color: gc.textSecondary, suffix: 'mg'),
),
const SizedBox(width: 8),
- const Spacer(flex: 2),
+ if (_minerals) ...[
+ Expanded(
+ child: _NumberField(label: t.ironLabel.toUpperCase(), controller: _fe, color: gc.danger, suffix: 'mg'),
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child:
+ _NumberField(label: t.potassiumLabel.toUpperCase(), controller: _ka, color: gc.sage, suffix: 'mg'),
+ ),
+ ] else
+ const Spacer(flex: 2),
]),
const SizedBox(height: 14),
Text(t.fatTypes.toUpperCase(),
diff --git a/lib/screens/nutrition/settings.dart b/lib/screens/nutrition/settings.dart
index eeb3098..e104823 100644
--- a/lib/screens/nutrition/settings.dart
+++ b/lib/screens/nutrition/settings.dart
@@ -48,6 +48,7 @@ Future<void> showTrackersSheet(BuildContext context) => _sheet<void>(context, (c
toggle(Tracker.fats, PhosphorIconsRegular.drop, gc.fat, t.fatTypes),
toggle(Tracker.fiber, PhosphorIconsRegular.leaf, gc.sage, t.fiberLabel),
toggle(Tracker.sugarSodium, PhosphorIconsRegular.cube, gc.carbs, t.sugarSodium),
+ toggle(Tracker.minerals, PhosphorIconsRegular.atom, gc.danger, t.mineralsTracker),
]),
label(t.trackersCards),
ToolGroup([
@@ -297,7 +298,7 @@ Future<void> showGoalsSheet(BuildContext context) => _sheet<void>(context, (cont
Text(t.addBurnedHint, textAlign: TextAlign.center, style: AppTheme.s(11.5, color: gc.textTertiary, height: 1.4)),
const SizedBox(height: 12),
ToolGroup(_waterRows(context)),
- if (fit.trackerOn(Tracker.fiber) || fit.trackerOn(Tracker.sugarSodium)) ...[
+ if (fit.trackerOn(Tracker.fiber) || fit.trackerOn(Tracker.sugarSodium) || fit.trackerOn(Tracker.minerals)) ...[
const SizedBox(height: 12),
ToolGroup([
if (fit.trackerOn(Tracker.fiber))
@@ -316,7 +317,24 @@ Future<void> showGoalsSheet(BuildContext context) => _sheet<void>(context, (cont
() => edit('${t.sodiumLimitLabel} (mg)', g.sodium,
(v) => fit.setNutritionGoals(g.copyWith(sodium: v.clamp(200, 20000))))),
],
+ if (fit.trackerOn(Tracker.minerals)) ...[
+ row(t.ironLabel, '${fit.ironGoal(g)} mg',
+ () => fit.setNutritionGoals(g.copyWith(iron: (fit.ironGoal(g) - 1).clamp(1, 200))),
+ () => fit.setNutritionGoals(g.copyWith(iron: (fit.ironGoal(g) + 1).clamp(1, 200))),
+ () => edit('${t.ironLabel} (mg)', fit.ironGoal(g),
+ (v) => fit.setNutritionGoals(g.copyWith(iron: v.clamp(1, 200))))),
+ row(t.potassiumLabel, '${fmt(fit.potassiumGoal(g) / 1000)} g',
+ () => fit.setNutritionGoals(g.copyWith(potassium: (fit.potassiumGoal(g) - 100).clamp(500, 20000))),
+ () => fit.setNutritionGoals(g.copyWith(potassium: (fit.potassiumGoal(g) + 100).clamp(500, 20000))),
+ () => edit('${t.potassiumLabel} (mg)', fit.potassiumGoal(g),
+ (v) => fit.setNutritionGoals(g.copyWith(potassium: v.clamp(500, 20000))))),
+ ],
]),
+ if (fit.trackerOn(Tracker.minerals)) ...[
+ const SizedBox(height: 8),
+ Text(t.mineralsHint,
+ textAlign: TextAlign.center, style: AppTheme.s(11.5, color: gc.textTertiary, height: 1.4)),
+ ],
],
const SizedBox(height: 16),
GhostButton(label: t.goalsFromProfile, icon: PhosphorIconsBold.sparkle, onTap: fit.useSuggestedGoals),
diff --git a/lib/screens/nutrition_screen.dart b/lib/screens/nutrition_screen.dart
index a4ba4d5..696322a 100644
--- a/lib/screens/nutrition_screen.dart
+++ b/lib/screens/nutrition_screen.dart
@@ -168,7 +168,7 @@ class _NutritionScreenState extends State<NutritionScreen> {
final planned = on(Tracker.plans) ? fit.planOn(fit.nutritionDay) : null;
final todayPlan = planned != null && planned.items.isNotEmpty ? planned : null;
final detail = <Widget>[
- if (on(Tracker.animal) || on(Tracker.fiber) || on(Tracker.sugarSodium)) _DetailGrid(),
+ if (on(Tracker.animal) || on(Tracker.fiber) || on(Tracker.sugarSodium) || on(Tracker.minerals)) _DetailGrid(),
if (on(Tracker.quality)) _QualityCard(),
if (on(Tracker.fats)) _FatTypesCard(),
if (on(Tracker.week)) _WeekTile(),
@@ -566,7 +566,7 @@ Widget _macroSummary(BuildContext context, Macros m) {
cell(t.macroCarbs, '${_g(m.carbs)} g', gc.carbs),
cell(t.macroFat, '${_g(m.fat)} g', gc.fat),
]),
- if (m.hasExtras) ...[
+ if (m.hasExtras || (fit.trackerOn(Tracker.minerals) && m.hasMinerals)) ...[
const SizedBox(height: 10),
Text(_extrasLine(m), style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textSecondary)),
],
diff --git a/lib/services/meal_ai.dart b/lib/services/meal_ai.dart
index f3eabde..c1a09a4 100644
--- a/lib/services/meal_ai.dart
+++ b/lib/services/meal_ai.dart
@@ -30,6 +30,8 @@ class AiFood {
this.trans,
this.mono,
this.poly,
+ this.iron,
+ this.potassium,
this.per100 = false,
this.meal = '',
});
@@ -50,6 +52,8 @@ class AiFood {
double? trans;
double? mono;
double? poly;
+ double? iron;
+ double? potassium;
bool per100;
String meal;
@@ -321,6 +325,8 @@ const _satKeys = ['saturated', 'saturatedfat', 'saturadas', 'saturada', 'grasass
const _transKeys = ['trans', 'transfat', 'transfats', 'grasastrans', 'grasatrans', 'transfatg'];
const _monoKeys = ['monounsaturated', 'monounsaturatedfat', 'monoinsaturadas', 'monoinsaturada', 'grasasmonoinsaturadas', 'monofat', 'mono'];
const _polyKeys = ['polyunsaturated', 'polyunsaturatedfat', 'poliinsaturadas', 'poliinsaturada', 'grasaspoliinsaturadas', 'polyfat', 'poly'];
+const _ironKeys = ['iron', 'hierro', 'ironmg', 'hierromg', 'eisen', 'fer', 'ferro'];
+const _potassiumKeys = ['potassium', 'potasio', 'potassiummg', 'potasiomg', 'kalium', 'potassio'];
const _nestedKeys = ['macros', 'nutrition', 'nutrients', 'nutrientes', 'nutritionalvalues', 'valoresnutricionales', 'totals', 'total', 'values'];
const _per100Keys = ['per100', 'per100g', 'per100grams', 'porcada100g', 'per100ml'];
const _mealKeys = ['meal', 'comida', 'slot', 'mealtype', 'momento'];
@@ -524,6 +530,8 @@ AiFood? _food(Object? raw, String defaultMeal) {
trans: macro(_transKeys),
mono: macro(_monoKeys),
poly: macro(_polyKeys),
+ iron: macro(_ironKeys),
+ potassium: macro(_potassiumKeys),
per100: isPer100,
meal: meal is String && meal.trim().isNotEmpty ? meal.trim() : defaultMeal,
);
@@ -836,6 +844,7 @@ Meal _mealFor(String raw, List<MealSlot> slots, Meal fallback) {
Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
var kcal = f.kcal, p = f.protein, c = f.carbs, fat = f.fat, fi = f.fiber;
var su = f.sugar, na = f.sodium, ch = f.chol, sa = f.sat, tr = f.trans, mu = f.mono, po = f.poly;
+ var fe = f.iron, ka = f.potassium;
if (f.per100) {
final k = (grams ?? 100) / 100;
kcal = kcal == null ? null : kcal * k;
@@ -850,6 +859,8 @@ Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
tr = tr == null ? null : tr * k;
mu = mu == null ? null : mu * k;
po = po == null ? null : po * k;
+ fe = fe == null ? null : fe * k;
+ ka = ka == null ? null : ka * k;
}
final given = [p, c, fat].where((e) => e != null).length;
final derived = (p ?? 0) * 4 + (c ?? 0) * 4 + (fat ?? 0) * 9;
@@ -890,6 +901,8 @@ Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
trans: tr ?? 0,
mono: mu ?? 0,
poly: po ?? 0,
+ iron: fe ?? 0,
+ potassium: ka ?? 0,
);
}
@@ -1079,7 +1092,7 @@ String buildMealAiPrompt(MealAiBrief b) {
'2. Use exactly the keys shown in the example. Keep "gymmane" as "$kMealAiTag" and "v" as $kMealAiVersion.',
'3. One entry in "items" per food or ingredient. Split mixed dishes into their ingredients (for example "Rice, cooked" and "Chicken breast, grilled").',
'4. "grams" is the weight in grams of that item (for liquids, the volume in millilitres). Always a plain number, never a range.',
- '5. "kcal", "protein", "carbs" and "fat" are the TOTAL for the amount in "grams", not per 100 g. Plain numbers only: dot as decimal separator, no units, no quotes. Protein, carbs and fat are in grams. kcal must be close to 4 x protein + 4 x carbs + 9 x fat. Optional, same rules (totals for the amount in "grams"): "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, and "sodium" and "cholesterol" in milligrams. Add them only when you know them, for example from a nutrition label I gave you; leave the key out otherwise, never write 0 for unknown.',
+ '5. "kcal", "protein", "carbs" and "fat" are the TOTAL for the amount in "grams", not per 100 g. Plain numbers only: dot as decimal separator, no units, no quotes. Protein, carbs and fat are in grams. kcal must be close to 4 x protein + 4 x carbs + 9 x fat. Optional, same rules (totals for the amount in "grams"): "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, and "sodium", "cholesterol", "iron" and "potassium" in milligrams. Add them only when you know them, for example from a nutrition label I gave you; leave the key out otherwise, never write 0 for unknown.',
'6. Use simple, common, generic food names (for example "Greek yogurt", "Rolled oats", "Banana", "Olive oil"). No brands, no adjectives, no cooking instructions inside the name. Add "cooked" or "grilled" to the name only when the weight is the cooked weight.',
'7. Use realistic amounts that a person can weigh at home. Do not put the same food twice in one option.',
'8. "meal" is one of these ids: ${ids.map((e) => '"$e"').join(', ')}.${b.day ? ' Spread the foods across the meals.' : ' Use "${b.mealId}" for every item.'}',
@@ -1185,7 +1198,7 @@ String buildFoodAiPrompt(String language) {
'FORMAT RULES (follow every one)',
'1. Reply with exactly one JSON object inside one ```json code block. Nothing before it, nothing after it.',
'2. Use exactly the keys shown in the example. Keep "gymmane" as "$kFoodAiTag" and "v" as 1.',
- '3. "per100" holds the values per 100 g (per 100 ml for drinks): "kcal", plus "protein", "carbs" and "fat" in grams. Optional, only when you know them: "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, "sodium" and "cholesterol" in milligrams. If the label gives salt instead of sodium, sodium in mg is salt in g x 400. Leave a key out when you do not know it, never write 0 for unknown.',
+ '3. "per100" holds the values per 100 g (per 100 ml for drinks): "kcal", plus "protein", "carbs" and "fat" in grams. Optional, only when you know them: "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, "sodium", "cholesterol", "iron" and "potassium" in milligrams. If the label gives salt instead of sodium, sodium in mg is salt in g x 400. Leave a key out when you do not know it, never write 0 for unknown.',
'4. Plain numbers only: dot as decimal separator, no units, no quotes.',
'5. "serving_name" is the serving the label uses, short (for example "1 bar" or "1 glass"), and "grams" is the weight of that serving in grams (millilitres for drinks). With no serving, use "100 g" and 100.',
'6. "liquid" is true for drinks and false for everything else.',
diff --git a/lib/state/nutrition_state.dart b/lib/state/nutrition_state.dart
index ab84056..ec7cc53 100644
--- a/lib/state/nutrition_state.dart
+++ b/lib/state/nutrition_state.dart
@@ -70,6 +70,8 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
fiber: (kcal * 14 / 1000).round().clamp(15, 60),
sugar: nutritionGoals.sugar,
sodium: nutritionGoals.sodium,
+ iron: nutritionGoals.iron,
+ potassium: nutritionGoals.potassium,
);
}
@@ -106,7 +108,23 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
final rest = restGoals;
if (rest == null || isTrainingDay(day)) return activeGoals;
final a = activeGoals;
- return rest.copyWith(waterMl: a.waterMl, glassMl: a.glassMl, fiber: a.fiber, sugar: a.sugar, sodium: a.sodium);
+ return rest.copyWith(
+ waterMl: a.waterMl,
+ glassMl: a.glassMl,
+ fiber: a.fiber,
+ sugar: a.sugar,
+ sodium: a.sodium,
+ iron: a.iron,
+ potassium: a.potassium);
+ }
+
+ int ironGoal(NutritionGoals g) => g.iron > 0 ? g.iron : (profile.sex == 'female' ? 18 : 8);
+
+ int potassiumGoal(NutritionGoals g) => g.potassium > 0 ? g.potassium : (profile.sex == 'female' ? 2600 : 3400);
+
+ ({int known, int total}) mineralsCoverage(DateTime day) {
+ final items = entriesOn(day).where((e) => e.total.kcal > 0).toList();
+ return (known: items.where((e) => e.total.hasMinerals).length, total: items.length);
}
static const double _liftMet = 5;
diff --git a/test/meal_ai_test.dart b/test/meal_ai_test.dart
index 2e30385..5e2bf43 100644
--- a/test/meal_ai_test.dart
+++ b/test/meal_ai_test.dart
@@ -459,7 +459,7 @@ void main() {
test('el prompt pide los campos opcionales sin hacerlos obligatorios', () {
final p = buildMealAiPrompt(brief);
- expect(p, contains('"sodium" and "cholesterol" in milligrams'));
+ expect(p, contains('"sodium", "cholesterol", "iron" and "potassium" in milligrams'));
expect(p, contains('leave the key out otherwise'));
});
});
@@ -486,6 +486,13 @@ void main() {
expect(pick.food.sodium, closeTo(40, 0.001));
});
+ test('#394 lee hierro y potasio y los pasa de 100 g a la ración', () {
+ final pick = parseFoodAi('{"food": {"name": "Lentejas", "grams": 200, "per100": {"kcal": 116, "protein": 9, "carbs": 20, "fat": 0.4, "iron": 3.3, "potassium": 369}}}');
+ expect(pick, isNotNull);
+ expect([pick!.food.iron, pick.food.potassium], [3.3, 369]);
+ expect(buildFoodAiPrompt('Spanish'), contains('"iron" and "potassium" in milligrams'));
+ });
+
test('sin valores no rellena nada', () {
expect(parseFoodAi('Mándame la etiqueta, una foto, un enlace o el nombre del alimento.'), isNull);
expect(parseFoodAi('{"food": {"name": "Pan"}}'), isNull);
diff --git a/test/nutrition_beta_keys.txt b/test/nutrition_beta_keys.txt
index da378ea..58285fa 100644
--- a/test/nutrition_beta_keys.txt
+++ b/test/nutrition_beta_keys.txt
@@ -359,3 +359,8 @@ fastErrShort
fastErrOverlap
fastSaved
fastAdjust
+mineralsTracker
+ironLabel
+potassiumLabel
+mineralsCoverage
+mineralsHint
diff --git a/test/nutrition_test.dart b/test/nutrition_test.dart
index 57fe971..0b80325 100644
--- a/test/nutrition_test.dart
+++ b/test/nutrition_test.dart
@@ -1141,4 +1141,42 @@ void main() {
expect(fit.activeSupplements, isEmpty);
});
});
+
+ group('#394 hierro y potasio', () {
+ test('viene apagado y no se enciende solo al cargar ajustes viejos', () {
+ expect(fit.trackerOn(Tracker.minerals), isFalse);
+ final old = fit.toJson();
+ final n = Map<String, dynamic>.from(old['nutrition'] as Map);
+ n['trackers'] = [for (final t in Tracker.values) if (t != Tracker.minerals && fit.trackerOn(t)) t.name];
+ old['nutrition'] = n;
+ expect(fit.tryApplyBackup(old), isTrue);
+ expect(fit.trackerOn(Tracker.minerals), isFalse);
+ });
+
+ test('se guardan, se suman y cuentan cuántos alimentos del día los traen', () {
+ const lentils = Macros(kcal: 230, protein: 18, carbs: 40, fat: 1, iron: 6.6, potassium: 738);
+ expect(Macros.fromJson(lentils.toJson()).iron, 6.6);
+ expect(Macros.fromJson(lentils.toJson()).potassium, 738);
+ expect(Macros.fromJson(whey.toJson()).hasMinerals, isFalse);
+ fit.logFood(fit.saveFood(name: 'Lentejas', serving: '1 plato', macros: lentils));
+ fit.logFood(fit.saveFood(name: 'Whey', serving: '30 g', macros: whey), servings: 2);
+ final day = DateTime.now();
+ expect(fit.totalOn(day).iron, closeTo(6.6, 0.001));
+ expect(fit.totalOn(day).potassium, 738);
+ final c = fit.mineralsCoverage(day);
+ expect((c.known, c.total), (1, 2));
+ });
+
+ test('las metas salen del perfil hasta que pones las tuyas, y viajan en la copia', () {
+ fit.updateProfile(sex: 'female');
+ expect(fit.ironGoal(fit.nutritionGoals), 18);
+ fit.updateProfile(sex: 'male');
+ expect(fit.ironGoal(fit.nutritionGoals), 8);
+ expect(fit.potassiumGoal(fit.nutritionGoals), 3400);
+ fit.setNutritionGoals(fit.nutritionGoals.copyWith(iron: 12, potassium: 4000));
+ final g = NutritionGoals.fromJson(fit.nutritionGoals.toJson());
+ expect((g.iron, g.potassium), (12, 4000));
+ expect(NutritionGoals.fromJson(const NutritionGoals().toJson()).iron, 0);
+ });
+ });
}