Skip to content

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

Nutrition screens adjustments

InlitX8325291b2ea7
diff --git a/lib/models/nutrition.dart b/lib/models/nutrition.dart
index 8840295..1285f09 100644
--- a/lib/models/nutrition.dart
+++ b/lib/models/nutrition.dart
@@ -412,21 +412,25 @@ double _servings(Object? v) {
}
class Recipe {
- const Recipe({required this.id, required this.name, required this.items});
+ const Recipe({required this.id, required this.name, required this.items, this.photo = ''});
final String id;
final String name;
final List<FoodEntry> items;
+ final String photo;
Macros get total => items.fold(Macros.zero, (s, e) => s + e.total);
- Recipe copyWith({String? name}) => Recipe(id: id, name: name ?? this.name, items: items);
+ Recipe copyWith({String? name, List<FoodEntry>? items, String? photo}) =>
+ Recipe(id: id, name: name ?? this.name, items: items ?? this.items, photo: photo ?? this.photo);
- Map<String, dynamic> toJson() => {'id': id, 'n': name, 'i': items.map((e) => e.toJson()).toList()};
+ Map<String, dynamic> toJson() =>
+ {'id': id, 'n': name, 'i': items.map((e) => e.toJson()).toList(), if (photo.isNotEmpty) 'ph': photo};
factory Recipe.fromJson(Map<String, dynamic> j) => Recipe(
id: j['id'] as String? ?? '',
name: j['n'] as String? ?? '',
+ photo: j['ph'] as String? ?? '',
items: [
for (final e in (j['i'] as List?) ?? const [])
if (e is Map) FoodEntry.fromJson(e.cast<String, dynamic>()),
diff --git a/lib/screens/nutrition/cards.dart b/lib/screens/nutrition/cards.dart
index 852979c..53c7245 100644
--- a/lib/screens/nutrition/cards.dart
+++ b/lib/screens/nutrition/cards.dart
@@ -879,6 +879,7 @@ Future<void> showShakePicker(BuildContext context) => _sheet<void>(context, (con
SizedBox(
height: 44,
child: ListView.separated(
+ key: const PageStorageKey('h-cards-882'),
scrollDirection: Axis.horizontal,
itemCount: others.length,
separatorBuilder: (_, _) => const SizedBox(width: 8),
@@ -946,9 +947,17 @@ const _suppPresets = [
String _suppPhoto(Supplement s) =>
s.photo.isEmpty || s.photo.endsWith('vessel-pills.webp') ? _suppPresets.first : s.photo;
-class _SupplementsCard extends StatelessWidget {
+class _SupplementsCard extends StatefulWidget {
const _SupplementsCard();
+ @override
+ State<_SupplementsCard> createState() => _SupplementsCardState();
+}
+
+class _SupplementsCardState extends State<_SupplementsCard> {
+ final _key = GlobalKey();
+ bool _wasFocused = false;
+
static List<String> get _suggested =>
[t.suppCreatine, t.suppVitaminD, t.suppOmega3, t.suppMagnesium, t.suppMultivitamin, t.suppCaffeine];
@@ -957,12 +966,22 @@ class _SupplementsCard extends StatelessWidget {
final gc = context.gc;
final day = fit.nutritionDay;
final taken = fit.takenOn(day);
+ final focused = fit.suppFocus.isNotEmpty;
+ if (focused && !_wasFocused) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ final c = _key.currentContext;
+ if (c != null && c.mounted) {
+ Scrollable.ensureVisible(c, duration: const Duration(milliseconds: 420), curve: Curves.easeOutCubic, alignment: 0.1);
+ }
+ });
+ }
+ _wasFocused = focused;
final list = fit.activeSupplements;
final archived = fit.archivedSuppList;
final due = [for (final s in list) if (s.dueOn(day)) s];
final later = [for (final s in list) if (!s.dueOn(day)) s];
final done = due.where((s) => taken.contains(s.id)).length;
- return SoftCard(
+ return KeyedSubtree(key: _key, child: SoftCard(
radius: 26,
padding: const EdgeInsets.fromLTRB(14, 14, 14, 12),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
@@ -1043,7 +1062,7 @@ class _SupplementsCard extends StatelessWidget {
),
),
]),
- );
+ ));
}
}
@@ -1112,7 +1131,13 @@ class _SupplementRow extends StatelessWidget {
decoration: BoxDecoration(
color: taken ? gc.sage.withValues(alpha: 0.14) : gc.bgRaised2,
borderRadius: BorderRadius.circular(18),
- border: Border.all(color: taken ? gc.sage.withValues(alpha: 0.45) : Colors.transparent),
+ border: Border.all(
+ color: fit.suppFocus.contains(supp.id) && !taken
+ ? gc.accent
+ : taken
+ ? gc.sage.withValues(alpha: 0.45)
+ : Colors.transparent,
+ width: fit.suppFocus.contains(supp.id) && !taken ? 2 : 1),
),
child: Row(children: [
SizedBox(
@@ -1533,7 +1558,7 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraft
const SizedBox(height: 10),
SizedBox(
height: 64,
- child: ListView(scrollDirection: Axis.horizontal, clipBehavior: Clip.none, children: [
+ child: ListView(key: const PageStorageKey('h-cards-1561'), scrollDirection: Axis.horizontal, clipBehavior: Clip.none, children: [
for (final p in _suppPresets) ...[option(p), const SizedBox(width: 10)],
for (final p in [_cutPhoto, _plainPhoto])
if (p != null) ...[option(p), const SizedBox(width: 10)],
@@ -1597,7 +1622,7 @@ class _SupplementEditorState extends State<_SupplementEditor> with _StickerDraft
const SizedBox(height: 8),
SizedBox(
height: 36,
- child: ListView(scrollDirection: Axis.horizontal, clipBehavior: Clip.none, children: [
+ child: ListView(key: const PageStorageKey('h-cards-1625'), scrollDirection: Axis.horizontal, clipBehavior: Clip.none, children: [
for (final u in kSuppUnits) ...[
_Chip(
label: fit.suppUnitLabel(u, _parsed(_amount) ?? 1),
diff --git a/lib/screens/nutrition/food.dart b/lib/screens/nutrition/food.dart
index 71992a7..fabf8c4 100644
--- a/lib/screens/nutrition/food.dart
+++ b/lib/screens/nutrition/food.dart
@@ -168,6 +168,7 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {
Widget _cats(GymColors gc) => SizedBox(
height: 92,
child: ListView(
+ key: const PageStorageKey('h-food-171'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
children: [
@@ -325,7 +326,7 @@ class _AddFoodSheetState extends State<_AddFoodSheet> {
);
Widget _recipeRow(Recipe r) => _FoodRow(
- leading: FoodPlate(items: _plateOf(r.items), size: 40),
+ leading: FoodPlate(items: _plateOf(r.items), size: 40, photo: r.photo),
title: r.name,
detail: '${_energy(r.total.kcal)} · ${t.recipeItems(r.items.length)}',
onTap: () => _openRecipe(r),
@@ -1156,6 +1157,7 @@ class _LogFoodSheetState extends State<_LogFoodSheet> {
if (food.byWeight) ...[
const SizedBox(height: 10),
SingleChildScrollView(
+ key: const PageStorageKey('h-food-1160'),
scrollDirection: Axis.horizontal,
child: Row(children: [
if (_fill case final fill?) ...[
@@ -1841,7 +1843,7 @@ mixin _StickerDrafts<T extends StatefulWidget> on State<T> {
if (source == null) return;
final shot = await ImagePicker().pickImage(source: source, maxWidth: 1400, maxHeight: 1400, imageQuality: 92);
if (shot == null || !mounted) return;
- final bytes = await File(shot.path).readAsBytes();
+ final bytes = await shot.readAsBytes();
if (!mounted) return;
setState(() => _working = true);
final draftFuture = prepareCutout(bytes);
@@ -2030,6 +2032,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
Widget _catPicker(GymColors gc) => SizedBox(
height: 40,
child: ListView(
+ key: const PageStorageKey('h-food-2035'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
children: [
diff --git a/lib/screens/nutrition/meals.dart b/lib/screens/nutrition/meals.dart
index e91bbc7..f827283 100644
--- a/lib/screens/nutrition/meals.dart
+++ b/lib/screens/nutrition/meals.dart
@@ -83,6 +83,7 @@ class _FoodShelf extends StatelessWidget {
return SizedBox(
height: 112,
child: ListView.separated(
+ key: const PageStorageKey('h-meals-86'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
itemCount: foods.length,
@@ -191,7 +192,7 @@ Future<void> showFavoritesSheet(BuildContext context) => _sheet<void>(context, (
Future<void> showSavedMealsSheet(BuildContext context) => _sheet<void>(context, (context) {
final gc = context.gc;
Widget recipeRow(Recipe r) => _FoodRow(
- leading: FoodPlate(items: _plateOf(r.items), size: 40),
+ leading: FoodPlate(items: _plateOf(r.items), size: 40, photo: r.photo),
title: r.name,
detail: '${_energy(r.total.kcal)} · ${t.recipeItems(r.items.length)}',
onTap: () async {
@@ -314,15 +315,11 @@ class _MealTabsState extends State<_MealTabs> {
final meals = fit.mealsShown;
final meal = fit.openMeal;
_reveal(meal);
- final shown = [
- for (final e in entries)
- if (e.meal == meal) e,
- ];
- final total = shown.fold(Macros.zero, (s, e) => s + e.total);
int count(Meal m) => entries.where((e) => e.meal == m).length;
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
SingleChildScrollView(
controller: _scroll,
+ key: const PageStorageKey('h-meals-322'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
child: Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
@@ -358,88 +355,142 @@ class _MealTabsState extends State<_MealTabs> {
]),
),
const SizedBox(height: 14),
- SoftCard(
- radius: 26,
- padding: const EdgeInsets.fromLTRB(16, 16, 12, 16),
- child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
- Row(children: [
- Pressable(
- onTap: () => showAddFoodSheet(context, meal),
- scale: 0.96,
- child: AnimatedSwitcher(
- duration: const Duration(milliseconds: 300),
- child: shown.isEmpty
- ? SizedBox(
- key: const ValueKey('empty'),
- width: 112,
- height: 112,
- child: Stack(alignment: Alignment.center, children: [
- const FoodPlate(items: [], size: 112),
- Icon(PhosphorIconsBold.plus, size: 24, color: gc.textTertiary),
- ]),
- )
- : FoodPlate(
- key: ValueKey(shown.length),
- items: [for (final e in shown.reversed) (fit.photoForEntry(e), e.name)],
- size: 112,
- ),
- ),
+ _MealCard(meal: meal),
+ ]);
+ }
+}
+
+class _MealCard extends StatelessWidget {
+ const _MealCard({required this.meal, this.compact = false});
+
+ final Meal meal;
+ final bool compact;
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final entries = fit.entriesOn(fit.nutritionDay);
+ final shown = [
+ for (final e in entries)
+ if (e.meal == meal) e,
+ ];
+ final total = shown.fold(Macros.zero, (s, e) => s + e.total);
+ final plate = compact ? 76.0 : 112.0;
+ return SoftCard(
+ radius: 26,
+ padding: const EdgeInsets.fromLTRB(16, 16, 12, 16),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ if (compact)
+ Padding(
+ padding: const EdgeInsetsDirectional.only(start: 2, bottom: 8),
+ child: Row(children: [
+ Expanded(child: Text(mealName(meal), style: AppTheme.f(16, weight: FontWeight.w800, color: gc.text))),
+ _roundIcon(PhosphorIconsBold.dotsThree, gc.textSecondary, () => showMealMenu(context, meal, shown), label: t.mealOptions),
+ ]),
+ ),
+ Row(children: [
+ Pressable(
+ onTap: () => showAddFoodSheet(context, meal),
+ scale: 0.96,
+ child: AnimatedSwitcher(
+ duration: const Duration(milliseconds: 300),
+ child: shown.isEmpty
+ ? SizedBox(
+ key: const ValueKey('empty'),
+ width: plate,
+ height: plate,
+ child: Stack(alignment: Alignment.center, children: [
+ FoodPlate(items: const [], size: plate),
+ Icon(PhosphorIconsBold.plus, size: 24, color: gc.textTertiary),
+ ]),
+ )
+ : FoodPlate(
+ key: ValueKey(shown.length),
+ items: [for (final e in shown.reversed) (fit.photoForEntry(e), e.name)],
+ size: plate,
+ ),
),
- const SizedBox(width: 16),
- Expanded(
- child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Ltr(child: Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [
- RollingText('${fit.energyOf(total.kcal)}',
- style: AppTheme.f(30, weight: FontWeight.w800, color: gc.text, height: 1.2)),
- const SizedBox(width: 5),
- Text(fit.energyUnit, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),
- ])),
- const SizedBox(height: 4),
- Text(
- shown.isEmpty ? t.nothingLogged : t.recipeItems(shown.length),
- style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textTertiary),
- ),
- const SizedBox(height: 10),
- Wrap(spacing: 6, runSpacing: 6, children: [
- _MacroPill(t.proteinLetter, total.protein, gc.protein),
- _MacroPill(t.carbsLetter, total.carbs, gc.carbs),
- _MacroPill(t.fatLetter, total.fat, gc.fat),
- ]),
+ ),
+ SizedBox(width: compact ? 12 : 16),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Ltr(child: Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [
+ RollingText('${fit.energyOf(total.kcal)}',
+ style: AppTheme.f(compact ? 24 : 30, weight: FontWeight.w800, color: gc.text, height: 1.2)),
+ const SizedBox(width: 5),
+ Text(fit.energyUnit, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),
+ ])),
+ const SizedBox(height: 4),
+ Text(
+ shown.isEmpty ? t.nothingLogged : t.recipeItems(shown.length),
+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textTertiary),
+ ),
+ const SizedBox(height: 10),
+ Wrap(spacing: 6, runSpacing: 6, children: [
+ _MacroPill(t.proteinLetter, total.protein, gc.protein),
+ _MacroPill(t.carbsLetter, total.carbs, gc.carbs),
+ _MacroPill(t.fatLetter, total.fat, gc.fat),
]),
- ),
- Align(
- alignment: Alignment.topRight,
- child: _roundIcon(PhosphorIconsBold.dotsThree, gc.textSecondary, () => showMealMenu(context, meal, shown),
- label: t.mealOptions),
- ),
- ]),
- if (shown.isEmpty && fit.trackerOn(Tracker.plans) && (fit.planOn(fit.nutritionDay)?.itemsOf(meal).isNotEmpty ?? false))
- _PlannedMeal(plan: fit.planOn(fit.nutritionDay)!, meal: meal),
- if (shown.isNotEmpty) ...[
- const SizedBox(height: 14),
- _EntryList(entries: shown),
- const SizedBox(height: 8),
- ],
+ ]),
+ ),
+ if (!compact)
+ Align(
+ alignment: Alignment.topRight,
+ child: _roundIcon(PhosphorIconsBold.dotsThree, gc.textSecondary, () => showMealMenu(context, meal, shown),
+ label: t.mealOptions),
+ ),
+ ]),
+ if (shown.isEmpty && fit.trackerOn(Tracker.plans) && (fit.planOn(fit.nutritionDay)?.itemsOf(meal).isNotEmpty ?? false))
+ _PlannedMeal(plan: fit.planOn(fit.nutritionDay)!, meal: meal),
+ if (shown.isNotEmpty) ...[
+ const SizedBox(height: 14),
+ _EntryList(entries: shown),
const SizedBox(height: 8),
- Row(children: [
- Expanded(
- child: PrimaryButton(
- label: t.addToMeal(mealInSentence(meal)),
- height: 52,
- onTap: () => showAddFoodSheet(context, meal),
- ),
- ),
- const SizedBox(width: 10),
- RoundAction(
- label: t.quickAdd,
- size: 50,
- onTap: () => showQuickAddSheet(context, meal),
- child: Icon(PhosphorIconsBold.lightning, size: 19, color: gc.warn),
+ ],
+ const SizedBox(height: 8),
+ Row(children: [
+ Expanded(
+ child: PrimaryButton(
+ label: compact ? t.addShort : t.addToMeal(mealInSentence(meal)),
+ height: compact ? 46 : 52,
+ onTap: () => showAddFoodSheet(context, meal),
),
- ]),
+ ),
+ const SizedBox(width: 10),
+ RoundAction(
+ label: t.quickAdd,
+ size: compact ? 44 : 50,
+ onTap: () => showQuickAddSheet(context, meal),
+ child: Icon(PhosphorIconsBold.lightning, size: 19, color: gc.warn),
+ ),
]),
- ),
- ]);
+ ]),
+ );
+ }
+}
+
+class _MealGrid extends StatelessWidget {
+ const _MealGrid();
+
+ @override
+ Widget build(BuildContext context) {
+ final meals = fit.mealsShown;
+ return LayoutBuilder(builder: (context, box) {
+ final n = (box.maxWidth / 250).floor().clamp(1, meals.length);
+ final rows = <Widget>[];
+ for (var i = 0; i < meals.length; i += n) {
+ if (i > 0) rows.add(const SizedBox(height: 16));
+ rows.add(IntrinsicHeight(
+ child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ for (var k = 0; k < n; k++) ...[
+ if (k > 0) const SizedBox(width: 16),
+ Expanded(child: i + k < meals.length ? _MealCard(meal: meals[i + k], compact: true) : const SizedBox.shrink()),
+ ],
+ ]),
+ ));
+ }
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: rows);
+ });
}
}
@@ -633,6 +684,23 @@ class _RecipeSheetState extends State<_RecipeSheet> {
showNotchToast(context, t.savedMealToast, subtitle: r.name, icon: PhosphorIconsFill.cookingPot, accent: context.gc.warn);
}
+ Future<void> _pickPhoto() async {
+ final id = widget.recipe.id;
+ final saved = await _pickRecipePhoto(context, _recipe.photo.isEmpty
+ ? null
+ : () {
+ fit.setRecipePhoto(id, '');
+ if (mounted) setState(() {});
+ });
+ if (saved == null) return;
+ if (!mounted || !fit.isOwnRecipe(id)) {
+ MediaStore.delete(saved);
+ return;
+ }
+ fit.setRecipePhoto(id, saved);
+ setState(() {});
+ }
+
Future<void> _delete() async {
final r = _recipe;
final ok = await askConfirm(context,
@@ -649,7 +717,11 @@ class _RecipeSheetState extends State<_RecipeSheet> {
final items = _items;
final total = items.fold(Macros.zero, (s, e) => s + e.total);
return _sheetFrame(context, [
- Center(child: FoodPlate(items: _plateOf(items), size: 128)),
+ Center(
+ child: _own
+ ? _PhotoPlate(items: items, photo: r.photo, size: 128, onTap: _pickPhoto)
+ : FoodPlate(items: _plateOf(items), size: 128, photo: r.photo),
+ ),
const SizedBox(height: 14),
SheetTitle(r.name, subtitle: t.recipeItems(items.length)),
const SizedBox(height: 18),
@@ -925,6 +997,7 @@ class _MealPicker extends StatelessWidget {
]);
}
return SingleChildScrollView(
+ key: const PageStorageKey('h-meals-1000'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
child: Row(children: [
@@ -969,6 +1042,55 @@ Future<void> showDishEditor(BuildContext context, {Recipe? recipe, Meal? meal})
builder: (_) => _DishEditor(recipe: recipe, meal: meal ?? fit.defaultMeal),
);
+Future<String?> _pickRecipePhoto(BuildContext context, VoidCallback? onRemove) async {
+ final source = await pickPhotoSource(context, onRemove: onRemove);
+ if (source == null || !context.mounted) return null;
+ final shot = await ImagePicker().pickImage(source: source, maxWidth: 1200, maxHeight: 1200, imageQuality: 86);
+ if (shot == null) return null;
+ return MediaStore.importFor('recipe', shot.path);
+}
+
+class _PhotoPlate extends StatelessWidget {
+ const _PhotoPlate({required this.items, required this.photo, required this.size, required this.onTap, this.empty});
+
+ final List<FoodEntry> items;
+ final String photo;
+ final double size;
+ final VoidCallback onTap;
+ final IconData? empty;
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ return Semantics(
+ button: true,
+ label: t.addPhoto,
+ child: Pressable(
+ onTap: onTap,
+ scale: 0.96,
+ child: Stack(clipBehavior: Clip.none, alignment: Alignment.center, children: [
+ FoodPlate(items: _plateOf(items), size: size, photo: photo),
+ if (empty != null && photo.isEmpty) Icon(empty, size: 26, color: gc.textTertiary),
+ PositionedDirectional(
+ end: -4,
+ bottom: 2,
+ child: Container(
+ width: 34,
+ height: 34,
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ shape: BoxShape.circle,
+ border: Border.all(color: gc.border),
+ ),
+ child: Icon(PhosphorIconsRegular.camera, size: 16, color: gc.text),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+}
+
class _DishEditor extends StatefulWidget {
const _DishEditor({this.recipe, required this.meal});
@@ -982,6 +1104,9 @@ class _DishEditor extends StatefulWidget {
class _DishEditorState extends State<_DishEditor> {
late final _name = TextEditingController(text: widget.recipe?.name ?? '');
late List<FoodEntry> _items = [...?widget.recipe?.items];
+ late String _photo = widget.recipe?.photo ?? '';
+ late String _kept = _photo;
+ final _fresh = <String>{};
bool _dirty = false;
bool get _own => widget.recipe != null && fit.isOwnRecipe(widget.recipe!.id);
@@ -989,9 +1114,33 @@ class _DishEditorState extends State<_DishEditor> {
@override
void dispose() {
_name.dispose();
+ for (final p in _fresh) {
+ if (p != _kept) MediaStore.delete(p);
+ }
super.dispose();
}
+ Future<void> _pickPhoto() async {
+ final saved = await _pickRecipePhoto(
+ context,
+ _photo.isEmpty
+ ? null
+ : () => setState(() {
+ _photo = '';
+ _dirty = true;
+ }));
+ if (saved == null) return;
+ if (!mounted) {
+ MediaStore.delete(saved);
+ return;
+ }
+ setState(() {
+ _photo = saved;
+ _fresh.add(saved);
+ _dirty = true;
+ });
+ }
+
void _set(List<FoodEntry> items) => setState(() {
_items = items;
_dirty = true;
@@ -1022,9 +1171,11 @@ class _DishEditorState extends State<_DishEditor> {
if (_own) {
fit.updateRecipe(r!.id, _items);
fit.renameRecipe(r.id, name);
+ fit.setRecipePhoto(r.id, _photo);
} else {
- fit.saveRecipe(name, _items);
+ fit.saveRecipe(name, _items, photo: _photo);
}
+ _kept = _photo;
_dirty = false;
HapticFeedback.lightImpact();
Navigator.of(context).pop();
@@ -1079,10 +1230,13 @@ class _DishEditorState extends State<_DishEditor> {
Expanded(
child: ListView(padding: EdgeInsets.zero, children: [
Center(
- child: Stack(alignment: Alignment.center, children: [
- FoodPlate(items: _plateOf(_items), size: 120),
- if (_items.isEmpty) Icon(PhosphorIconsBold.cookingPot, size: 26, color: gc.textTertiary),
- ]),
+ child: _PhotoPlate(
+ items: _items,
+ photo: _photo,
+ size: 120,
+ onTap: _pickPhoto,
+ empty: _items.isEmpty ? PhosphorIconsBold.cookingPot : null,
+ ),
),
const SizedBox(height: 14),
_TextInput(controller: _name, hint: t.dishNameHint, label: t.nameLabel),
diff --git a/lib/screens/nutrition/plans.dart b/lib/screens/nutrition/plans.dart
index 94d5bef..1e65ceb 100644
--- a/lib/screens/nutrition/plans.dart
+++ b/lib/screens/nutrition/plans.dart
@@ -14,15 +14,9 @@ Future<void> shareMealPlans(List<MealPlan> plans) async {
if (plans.isEmpty) return;
final name = plans.length == 1 ? plans.first.name : t.mealPlansTitle;
try {
- final dir = await getTemporaryDirectory();
final slug = name.toLowerCase().replaceAll(RegExp(r'[^a-z0-9]+'), '-').replaceAll(RegExp(r'^-+|-+$'), '');
- final file = File('${dir.path}/gymmane-${slug.isEmpty ? 'plan' : slug}.json');
- await file.writeAsString(fit.exportMealPlansJson(plans));
- await SharePlus.instance.share(ShareParams(
- files: [XFile(file.path, mimeType: 'application/json')],
- text: [for (final p in plans) _planSummary(p)].join('\n\n'),
- subject: name,
- ));
+ await shareFile('gymmane-${slug.isEmpty ? 'plan' : slug}.json', utf8Bytes(fit.exportMealPlansJson(plans)),
+ mime: 'application/json', text: [for (final p in plans) _planSummary(p)].join('\n\n'), subject: name);
} catch (_) {}
}
@@ -280,6 +274,7 @@ Future<void> showMealPlanEditor(BuildContext context, {MealPlan? plan, Set<int>
isScrollControlled: true,
enableDrag: false,
backgroundColor: Colors.transparent,
+ maxWidth: 940,
builder: (_) => _PlanEditor(plan: plan, days: days),
);
@@ -480,6 +475,145 @@ class _PlanEditorState extends State<_PlanEditor> {
final total = plan.total;
final logged = fit.entriesOn(fit.nutritionDay).isNotEmpty;
final start = fit.weekStartDay;
+ final headPart = <Widget>[
+ Row(children: [
+ FoodPlate(items: _plateOf(plan.items), size: 76),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ TextField(
+ controller: _name,
+ onChanged: (_) => _dirty = true,
+ textCapitalization: TextCapitalization.sentences,
+ style: AppTheme.f(21, weight: FontWeight.w800, color: gc.text),
+ cursorColor: gc.accent,
+ decoration: InputDecoration(
+ isDense: true,
+ border: InputBorder.none,
+ hintText: t.planNameHint,
+ hintStyle: AppTheme.f(21, weight: FontWeight.w700, color: gc.textTertiary),
+ contentPadding: EdgeInsets.zero,
+ suffixIcon: Icon(PhosphorIconsRegular.pencilSimple, size: 15, color: gc.textTertiary),
+ suffixIconConstraints: const BoxConstraints(minWidth: 20, minHeight: 20),
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(_planDetail(plan), style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary)),
+ ]),
+ ),
+ ]),
+ const SizedBox(height: 14),
+ _macroSummary(context, total),
+ const SizedBox(height: 18),
+ _kicker(gc, t.planDaysQuestion.toUpperCase()),
+ const SizedBox(height: 8),
+ Row(children: [
+ for (var i = 0; i < 7; i++)
+ Builder(builder: (context) {
+ final d = (start - 1 + i) % 7 + 1;
+ final on = _days.contains(d);
+ final other = fit.mealWeek[d];
+ final taken = !on && other != null && other != plan.id;
+ return Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 3),
+ child: Pressable(
+ scale: 0.92,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ setState(() {
+ _days = {..._days};
+ if (!_days.remove(d)) _days.add(d);
+ _dirty = true;
+ });
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 180),
+ height: 40,
+ decoration: BoxDecoration(
+ color: on ? gc.accent : gc.bgRaised2,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ alignment: Alignment.center,
+ child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Text(t.weekdayInitial(d),
+ style: AppTheme.f(13,
+ weight: FontWeight.w800, color: on ? gc.onEmber : gc.textSecondary)),
+ if (taken)
+ Container(
+ width: 4,
+ height: 4,
+ margin: const EdgeInsets.only(top: 2),
+ decoration: BoxDecoration(color: gc.textTertiary, shape: BoxShape.circle),
+ ),
+ ]),
+ ),
+ ),
+ ),
+ );
+ }),
+ ]),
+ const SizedBox(height: 8),
+ Text(_days.isEmpty ? t.planDaysNone : t.planDaysHint,
+ style: AppTheme.s(11.5, color: gc.textTertiary, height: 1.4)),
+ if (plan.items.isEmpty) ...[
+ const SizedBox(height: 16),
+ Wrap(spacing: 7, runSpacing: 7, children: [
+ if (logged)
+ _Chip(
+ label: t.planFromDay,
+ icon: PhosphorIconsBold.copy,
+ onTap: () => _setItems(fit.draftMealPlan(fromDay: true).items),
+ ),
+ if (_isNew)
+ _Chip(
+ label: t.planImport,
+ icon: PhosphorIconsBold.downloadSimple,
+ onTap: () async {
+ _dirty = false;
+ final nav = Navigator.of(context)..pop();
+ await importMealPlanFile(nav.context);
+ },
+ ),
+ ]),
+ ],
+ ];
+ Widget slotOf(MealSlot slot) => Column(crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [
+ Row(children: [
+ Icon(_mealIcon(slot.meal), size: 14, color: gc.textSecondary),
+ const SizedBox(width: 6),
+ Expanded(child: _kicker(gc, mealName(slot.meal).toUpperCase())),
+ if (plan.itemsOf(slot.meal).isNotEmpty)
+ Text(_energy(plan.itemsOf(slot.meal).fold(Macros.zero, (s, e) => s + e.total).kcal),
+ style: AppTheme.f(12, weight: FontWeight.w800, color: gc.textSecondary)),
+ ]),
+ const SizedBox(height: 8),
+ for (final e in plan.itemsOf(slot.meal)) _item(gc, e),
+ Pressable(
+ scale: 0.98,
+ onTap: () => _add(slot.meal),
+ child: Container(
+ height: 44,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: gc.border),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(PhosphorIconsBold.plus, size: 13, color: gc.accent),
+ const SizedBox(width: 6),
+ Text(t.addToMeal(mealInSentence(slot.meal)),
+ style: AppTheme.f(12.5, weight: FontWeight.w800, color: gc.accent)),
+ ]),
+ ),
+ ),
+ ]);
+ final logPart = <Widget>[
+ if (!_isNew && plan.items.isNotEmpty) ...[
+ const SizedBox(height: 18),
+ GhostButton(label: t.planLogDay, icon: PhosphorIconsBold.checkCircle, onTap: _logToday),
+ ],
+ ];
+ final desk = DesktopScope.wideFor(media.size.width);
return PopScope(
canPop: !_dirty,
onPopInvokedWithResult: (didPop, _) {
@@ -488,7 +622,7 @@ class _PlanEditorState extends State<_PlanEditor> {
child: Padding(
padding: EdgeInsets.only(bottom: media.viewInsets.bottom),
child: Container(
- height: media.size.height * 0.92,
+ height: desk ? (media.size.height * 0.86).clamp(0.0, 640.0) : media.size.height * 0.92,
padding: EdgeInsets.fromLTRB(20, 12, 20, 14 + media.padding.bottom),
decoration: sheetDecoration(gc),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
@@ -515,144 +649,32 @@ class _PlanEditorState extends State<_PlanEditor> {
]),
const SizedBox(height: 12),
Expanded(
- child: ListView(clipBehavior: Clip.hardEdge, padding: EdgeInsets.zero, children: [
- Row(children: [
- FoodPlate(items: _plateOf(plan.items), size: 76),
- const SizedBox(width: 14),
- Expanded(
- child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- TextField(
- controller: _name,
- onChanged: (_) => _dirty = true,
- textCapitalization: TextCapitalization.sentences,
- style: AppTheme.f(21, weight: FontWeight.w800, color: gc.text),
- cursorColor: gc.accent,
- decoration: InputDecoration(
- isDense: true,
- border: InputBorder.none,
- hintText: t.planNameHint,
- hintStyle: AppTheme.f(21, weight: FontWeight.w700, color: gc.textTertiary),
- contentPadding: EdgeInsets.zero,
- suffixIcon: Icon(PhosphorIconsRegular.pencilSimple, size: 15, color: gc.textTertiary),
- suffixIconConstraints: const BoxConstraints(minWidth: 20, minHeight: 20),
- ),
- ),
- const SizedBox(height: 4),
- Text(_planDetail(plan), style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.textSecondary)),
- ]),
- ),
- ]),
- const SizedBox(height: 14),
- _macroSummary(context, total),
- const SizedBox(height: 18),
- _kicker(gc, t.planDaysQuestion.toUpperCase()),
- const SizedBox(height: 8),
- Row(children: [
- for (var i = 0; i < 7; i++)
- Builder(builder: (context) {
- final d = (start - 1 + i) % 7 + 1;
- final on = _days.contains(d);
- final other = fit.mealWeek[d];
- final taken = !on && other != null && other != plan.id;
- return Expanded(
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 3),
- child: Pressable(
- scale: 0.92,
- onTap: () {
- HapticFeedback.selectionClick();
- setState(() {
- _days = {..._days};
- if (!_days.remove(d)) _days.add(d);
- _dirty = true;
- });
- },
- child: AnimatedContainer(
- duration: const Duration(milliseconds: 180),
- height: 40,
- decoration: BoxDecoration(
- color: on ? gc.accent : gc.bgRaised2,
- borderRadius: BorderRadius.circular(12),
- ),
- alignment: Alignment.center,
- child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
- Text(t.weekdayInitial(d),
- style: AppTheme.f(13,
- weight: FontWeight.w800, color: on ? gc.onEmber : gc.textSecondary)),
- if (taken)
- Container(
- width: 4,
- height: 4,
- margin: const EdgeInsets.only(top: 2),
- decoration: BoxDecoration(color: gc.textTertiary, shape: BoxShape.circle),
- ),
- ]),
- ),
- ),
- ),
- );
- }),
- ]),
- const SizedBox(height: 8),
- Text(_days.isEmpty ? t.planDaysNone : t.planDaysHint,
- style: AppTheme.s(11.5, color: gc.textTertiary, height: 1.4)),
- if (plan.items.isEmpty) ...[
- const SizedBox(height: 16),
- Wrap(spacing: 7, runSpacing: 7, children: [
- if (logged)
- _Chip(
- label: t.planFromDay,
- icon: PhosphorIconsBold.copy,
- onTap: () => _setItems(fit.draftMealPlan(fromDay: true).items),
- ),
- if (_isNew)
- _Chip(
- label: t.planImport,
- icon: PhosphorIconsBold.downloadSimple,
- onTap: () async {
- _dirty = false;
- final nav = Navigator.of(context)..pop();
- await importMealPlanFile(nav.context);
- },
+ child: desk
+ ? Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ SizedBox(
+ width: 330,
+ child: ListView(clipBehavior: Clip.hardEdge, padding: EdgeInsets.zero, children: [...headPart, ...logPart]),
),
- ]),
- ],
- for (final slot in fit.mealSlots) ...[
- const SizedBox(height: 18),
- Row(children: [
- Icon(_mealIcon(slot.meal), size: 14, color: gc.textSecondary),
- const SizedBox(width: 6),
- Expanded(child: _kicker(gc, mealName(slot.meal).toUpperCase())),
- if (plan.itemsOf(slot.meal).isNotEmpty)
- Text(_energy(plan.itemsOf(slot.meal).fold(Macros.zero, (s, e) => s + e.total).kcal),
- style: AppTheme.f(12, weight: FontWeight.w800, color: gc.textSecondary)),
- ]),
- const SizedBox(height: 8),
- for (final e in plan.itemsOf(slot.meal)) _item(gc, e),
- Pressable(
- scale: 0.98,
- onTap: () => _add(slot.meal),
- child: Container(
- height: 44,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(14),
- border: Border.all(color: gc.border),
+ const SizedBox(width: 26),
+ Expanded(
+ child: ListView(clipBehavior: Clip.hardEdge, padding: EdgeInsets.zero, children: [
+ for (var i = 0; i < fit.mealSlots.length; i += 2) ...[
+ if (i > 0) const SizedBox(height: 18),
+ Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Expanded(child: slotOf(fit.mealSlots[i])),
+ const SizedBox(width: 16),
+ Expanded(child: i + 1 < fit.mealSlots.length ? slotOf(fit.mealSlots[i + 1]) : const SizedBox.shrink()),
+ ]),
+ ],
+ ]),
),
- child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
- Icon(PhosphorIconsBold.plus, size: 13, color: gc.accent),
- const SizedBox(width: 6),
- Text(t.addToMeal(mealInSentence(slot.meal)),
- style: AppTheme.f(12.5, weight: FontWeight.w800, color: gc.accent)),
- ]),
- ),
- ),
- ],
- if (!_isNew && plan.items.isNotEmpty) ...[
- const SizedBox(height: 18),
- GhostButton(label: t.planLogDay, icon: PhosphorIconsBold.checkCircle, onTap: _logToday),
- ],
- const SizedBox(height: 16),
- ]),
+ ])
+ : ListView(clipBehavior: Clip.hardEdge, padding: EdgeInsets.zero, children: [
+ ...headPart,
+ for (final slot in fit.mealSlots) ...[const SizedBox(height: 18), slotOf(slot)],
+ ...logPart,
+ const SizedBox(height: 16),
+ ]),
),
const SizedBox(height: 10),
PrimaryButton(label: _isNew ? t.planSave : t.save, onTap: _save),
diff --git a/lib/screens/nutrition/prep.dart b/lib/screens/nutrition/prep.dart
index 310a5cd..864cbe2 100644
--- a/lib/screens/nutrition/prep.dart
+++ b/lib/screens/nutrition/prep.dart
@@ -35,6 +35,7 @@ class _PrepShelf extends StatelessWidget {
return SizedBox(
height: 150,
child: ListView.separated(
+ key: const PageStorageKey('h-prep-38'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
itemCount: list.length,
@@ -411,6 +412,7 @@ class _DayStrip extends StatelessWidget {
}
return SingleChildScrollView(
+ key: const PageStorageKey('h-prep-415'),
scrollDirection: Axis.horizontal,
clipBehavior: Clip.none,
child: Row(children: [
diff --git a/lib/screens/nutrition_screen.dart b/lib/screens/nutrition_screen.dart
index e6eb1bf..a4ba4d5 100644
--- a/lib/screens/nutrition_screen.dart
+++ b/lib/screens/nutrition_screen.dart
@@ -1,15 +1,13 @@
import 'dart:async';
-import 'dart:io';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
-import 'package:path_provider/path_provider.dart';
import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
-import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
+import '../app/desktop.dart';
import '../l10n/l10n.dart';
import '../models/nutrition.dart';
import '../services/food_library.dart';
@@ -31,6 +29,7 @@ import '../widgets/rolling_text.dart';
import '../widgets/cutout_editor.dart';
import '../widgets/ruler_picker.dart';
import '../widgets/ui_kit.dart';
+import '../services/file_share.dart';
import 'plan_import_sheet.dart' show pickTextFile;
import 'progress_screen.dart' show showBodyweightSheet;
@@ -175,6 +174,83 @@ class _NutritionScreenState extends State<NutritionScreen> {
if (on(Tracker.week)) _WeekTile(),
if (on(Tracker.weight)) _WeightTile(),
];
+ final header = ScreenHeader(
+ title: t.nutrition,
+ subtitle: _dayLabel,
+ onBack: fit.backFromNutrition,
+ badge: BetaTag(t.sectionBeta),
+ actions: [
+ RoundAction(
+ label: t.trackersTitle,
+ onTap: () => showTrackersSheet(context),
+ child: Icon(PhosphorIconsRegular.slidersHorizontal, size: 17, color: gc.textSecondary),
+ ),
+ const SizedBox(width: 8),
+ RoundAction(
+ label: t.nutritionGoals,
+ onTap: () => showGoalsSheet(context),
+ child: Icon(PhosphorIconsRegular.target, size: 17, color: gc.textSecondary),
+ ),
+ ],
+ );
+ if (DesktopScope.of(context)) {
+ Widget stack(List<Widget> ws, {double gap = 12}) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (var i = 0; i < ws.length; i++) ...[if (i > 0) SizedBox(height: gap), ws[i]],
+ ],
+ );
+ final tiles = <(int, Widget)>[
+ (0, stack([
+ if (on(Tracker.calories) || on(Tracker.protein) || on(Tracker.carbs) || on(Tracker.fat)) _HeroCard(),
+ const _SearchBar(),
+ if (on(Tracker.foods)) _FoodShelf(),
+ ])),
+ if (on(Tracker.week)) (0, _WeekTile()),
+ for (final c in cards) (1, c),
+ if (todayPlan != null) (2, _TodayPlanCard(plan: todayPlan)),
+ if (on(Tracker.prep))
+ (2, stack([
+ _Heading(t.prepTitle, action: t.prepNewShort, onAction: () => showBatchEditor(context)),
+ _PrepShelf(),
+ ])),
+ if (on(Tracker.plans))
+ (2, stack([
+ _Heading(t.mealPlansTitle, action: t.mealPlanNew, onAction: () => showNewPlanSheet(context)),
+ _PlansSection(),
+ ])),
+ if (on(Tracker.foods)) (2, _Folders()),
+ ];
+ final rest = [for (final d in detail) if (d is! _WeekTile) d];
+ var at = 2;
+ Widget rise(Widget w) => Rise(index: at++, child: w);
+ final top = [for (final x in tiles) FlowSlot(column: x.$1, stretch: x.$2 is _WeekTile || x.$2 is _SupplementsCard, child: rise(x.$2))];
+ final meals = rise(const _MealGrid());
+ final low = [for (final d in rest) rest.length == 1 ? FlowWide(child: rise(d)) : rise(d)];
+ return RiseScope(
+ id: 'nutrition',
+ child: SingleChildScrollView(
+ clipBehavior: Clip.none,
+ padding: const EdgeInsets.fromLTRB(32, 30, 32, 48),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Rise(index: 0, child: header),
+ const SizedBox(height: 16),
+ Rise(index: 1, child: _WeekStrip()),
+ const SizedBox(height: 18),
+ CardFlow(minColumn: 340, gap: 20, children: top),
+ const SizedBox(height: 30),
+ meals,
+ if (low.isNotEmpty) ...[
+ const SizedBox(height: 30),
+ _Heading(t.trackersDetail),
+ const SizedBox(height: 12),
+ CardFlow(minColumn: 340, gap: 20, children: low),
+ ],
+ ]),
+ ),
+ );
+ }
var order = 0;
return RiseScope(
id: 'nutrition',
@@ -186,25 +262,7 @@ class _NutritionScreenState extends State<NutritionScreen> {
padding: const EdgeInsets.fromLTRB(20, 12, 20, 40),
children: [
for (final w in <Widget>[
- ScreenHeader(
- title: t.nutrition,
- subtitle: _dayLabel,
- onBack: fit.backFromNutrition,
- badge: BetaTag(t.sectionBeta),
- actions: [
- RoundAction(
- label: t.trackersTitle,
- onTap: () => showTrackersSheet(context),
- child: Icon(PhosphorIconsRegular.slidersHorizontal, size: 17, color: gc.textSecondary),
- ),
- const SizedBox(width: 8),
- RoundAction(
- label: t.nutritionGoals,
- onTap: () => showGoalsSheet(context),
- child: Icon(PhosphorIconsRegular.target, size: 17, color: gc.textSecondary),
- ),
- ],
- ),
+ header,
const SizedBox(height: 16),
_WeekStrip(),
if (on(Tracker.calories) || on(Tracker.protein) || on(Tracker.carbs) || on(Tracker.fat)) ...[
diff --git a/lib/state/nutrition_state.dart b/lib/state/nutrition_state.dart
index ff10f24..e346433 100644
--- a/lib/state/nutrition_state.dart
+++ b/lib/state/nutrition_state.dart
@@ -751,7 +751,7 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
void updateRecipe(String id, List<FoodEntry> items) {
final i = recipes.indexWhere((r) => r.id == id);
if (i < 0 || items.isEmpty) return;
- recipes[i] = Recipe(id: id, name: recipes[i].name, items: items);
+ recipes[i] = recipes[i].copyWith(items: items);
_persist();
notifyListeners();
}
@@ -835,13 +835,14 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
return out;
}
- Recipe? saveRecipe(String name, List<FoodEntry> items) {
+ Recipe? saveRecipe(String name, List<FoodEntry> items, {String photo = ''}) {
final clean = name.trim();
if (clean.isEmpty || items.isEmpty) return null;
final r = Recipe(
id: _newId('r'),
name: clean,
items: [for (final e in items) e.copyWith(id: _newId('e'))],
+ photo: photo,
);
recipes.add(r);
_persist();
@@ -849,6 +850,17 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
return r;
}
+ void setRecipePhoto(String id, String photo) {
+ final i = recipes.indexWhere((r) => r.id == id);
+ if (i < 0) return;
+ final old = recipes[i].photo;
+ if (old == photo) return;
+ if (old.isNotEmpty && !isAssetPhoto(old)) MediaStore.delete(old);
+ recipes[i] = recipes[i].copyWith(photo: photo);
+ _persist();
+ notifyListeners();
+ }
+
void renameRecipe(String id, String name) {
final i = recipes.indexWhere((r) => r.id == id);
if (i < 0 || name.trim().isEmpty) return;
@@ -935,6 +947,9 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
void deleteRecipe(String id) {
archivedRecipes.remove(id);
+ for (final r in recipes) {
+ if (r.id == id && r.photo.isNotEmpty && !isAssetPhoto(r.photo)) MediaStore.delete(r.photo);
+ }
recipes.removeWhere((r) => r.id == id);
_persist();
notifyListeners();
@@ -1562,6 +1577,25 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
notifyListeners();
}
+ void takeSupplementsOn(DateTime day, List<String> ids) {
+ final key = _dk(day);
+ final taken = supplementsTaken.putIfAbsent(key, () => <String>{});
+ var changed = false;
+ for (final id in ids) {
+ final i = supplements.indexWhere((s) => s.id == id);
+ if (i < 0 || !taken.add(id)) continue;
+ changed = true;
+ final s = supplements[i];
+ final stock = s.stock;
+ if (stock != null) supplements[i] = s.copyWith(stock: math.max(0.0, stock - s.perTake));
+ }
+ if (taken.isEmpty) supplementsTaken.remove(key);
+ if (!changed) return;
+ syncSupplementReminder();
+ _persist();
+ notifyListeners();
+ }
+
void setSupplementReminder(int? minuteOfDay) {
supplementReminderMin = minuteOfDay?.clamp(0, 24 * 60 - 1);
syncSupplementReminder();
@@ -1600,6 +1634,7 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
for (final d in due)
(
at: d.at,
+ ids: [for (final s in d.items) s.id],
names: [for (final s in d.items) s.name],
doses: [
for (final s in d.items)
@@ -1670,6 +1705,22 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
pushRoute('nutrition');
}
+ Set<String> suppFocus = {};
+ int _suppFocusTicket = 0;
+
+ void openSupplements(List<String> ids) {
+ if (!nutritionBeta) return;
+ if (route != 'nutrition') goNutrition();
+ suppFocus = ids.toSet();
+ final ticket = ++_suppFocusTicket;
+ notifyListeners();
+ Future.delayed(const Duration(seconds: 6), () {
+ if (ticket != _suppFocusTicket) return;
+ suppFocus = {};
+ notifyListeners();
+ });
+ }
+
void backFromNutrition() => popRoute();
static const fastPresets = [12, 14, 16, 18, 20, 23];
@@ -1869,7 +1920,10 @@ mixin NutritionState on FitCore, ToolsState, StatsState {
weightAim = const {'lose', 'gain', 'hold'}.contains(aim) ? aim as String : '';
recipes
..clear()
- ..addAll(list('recipes').map(Recipe.fromJson).where((r) => r.id.isNotEmpty && r.items.isNotEmpty));
+ ..addAll(list('recipes').map(Recipe.fromJson).where((r) => r.id.isNotEmpty && r.items.isNotEmpty).map((r) {
+ if (restored == null || r.photo.isEmpty || isAssetPhoto(r.photo)) return r;
+ return r.copyWith(photo: restored[r.photo] ?? '');
+ }));
archivedRecipes
..clear()
..addAll([for (final id in (j?['recArch'] as List?) ?? const []) if (id is String && recipes.any((r) => r.id == id)) id]);
diff --git a/lib/widgets/nutrition_art.dart b/lib/widgets/nutrition_art.dart
index c4c8221..fb7f873 100644
--- a/lib/widgets/nutrition_art.dart
+++ b/lib/widgets/nutrition_art.dart
@@ -1,4 +1,3 @@
-import 'dart:io';
import 'dart:math' as math;
import 'dart:ui' as ui show Image, Picture, PictureRecorder;
@@ -11,6 +10,7 @@ import '../services/food_library.dart';
import '../services/media_store.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
+import 'local_image.dart';
extension NutritionColors on GymColors {
Color get water => info;
@@ -198,12 +198,11 @@ class FoodSticker extends StatelessWidget {
final gc = context.gc;
final asset = isAssetPhoto(photo);
final path = photo.isEmpty || asset ? null : MediaStore.pathFor(photo);
- final file = path == null ? null : File(path);
final angle = tilt ? ((name.hashCode % 9) - 4) * 0.012 : 0.0;
final px = (size * MediaQuery.devicePixelRatioOf(context)).round();
final cache = asset && px >= 300 ? null : px;
Widget art;
- if (asset || file != null) {
+ if (asset || path != null) {
final image = asset
? Image.asset(assetOfPhoto(photo),
width: size,
@@ -213,12 +212,12 @@ class FoodSticker extends StatelessWidget {
cacheWidth: cache,
opacity: dim ? _faded : null,
errorBuilder: (_, _, _) => _Placeholder(name: name, size: size, gc: gc))
- : Image.file(file!,
+ : Image(
+ image: ResizeImage.resizeIfNeeded(cache, null, localImage(path!)),
width: size,
height: size,
fit: BoxFit.contain,
gaplessPlayback: true,
- cacheWidth: cache,
opacity: dim ? _faded : null,
errorBuilder: (_, _, _) => _Placeholder(name: name, size: size, gc: gc));
art = !shadow
@@ -858,11 +857,12 @@ class _VesselPainter extends CustomPainter {
}
class FoodPlate extends StatelessWidget {
- const FoodPlate({super.key, required this.items, this.size = 150, this.wrap});
+ const FoodPlate({super.key, required this.items, this.size = 150, this.wrap, this.photo = ''});
final List<(String photo, String name)> items;
final double size;
final Widget Function(int i, Widget child)? wrap;
+ final String photo;
static const _layouts = <List<(double, double, double)>>[
[],
@@ -876,8 +876,10 @@ class FoodPlate extends StatelessWidget {
@override
Widget build(BuildContext context) {
final gc = context.gc;
- final shown = items.take(5).toList();
+ final path = photo.isEmpty || isAssetPhoto(photo) ? null : MediaStore.pathFor(photo);
+ final shown = path == null ? items.take(5).toList() : const <(String, String)>[];
final layout = _layouts[shown.length];
+ final inset = size * 0.1;
return SizedBox(
width: size,
height: size,
@@ -901,6 +903,37 @@ class FoodPlate extends StatelessWidget {
),
),
),
+ if (path != null)
+ Positioned.fill(
+ left: inset,
+ top: inset,
+ right: inset,
+ bottom: inset,
+ child: ClipOval(
+ child: Image(
+ image: ResizeImage.resizeIfNeeded(
+ ((size - inset * 2) * MediaQuery.devicePixelRatioOf(context)).round(), null, localImage(path)),
+ fit: BoxFit.cover,
+ gaplessPlayback: true,
+ errorBuilder: (_, _, _) => const SizedBox.shrink(),
+ ),
+ ),
+ ),
+ if (path != null)
+ Positioned.fill(
+ left: inset,
+ top: inset,
+ right: inset,
+ bottom: inset,
+ child: IgnorePointer(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ border: Border.all(color: Colors.black.withValues(alpha: 0.22), width: math.max(1, size * 0.012)),
+ ),
+ ),
+ ),
+ ),
for (var i = 0; i < shown.length; i++)
Positioned(
left: size / 2 + layout[i].$1 * size - layout[i].$3 * size / 2,