The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
314 lines
15 KiB
Dart
314 lines
15 KiB
Dart
// The meal builder (the web page's #fd-meal): a meal = one of My foods made of others. Name,
|
||
// ingredients (a food + amount + unit, or an entry's own numbers), the total, "weight when done"
|
||
// (soup boils down / takes on water; empty = the ingredients' sum), per 100 g, portions ("whole meal"
|
||
// is added by itself), note. Saving works the values out from the ingredients as they are now.
|
||
// Ways in: My foods (a meal, or + ▸ New meal) and Food ⋮ ▸ Make a meal (from the day's entries:
|
||
// "put them together as one entry" replaces them by one entry of the meal — the day's total stays).
|
||
import 'package:flutter/material.dart';
|
||
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import 'food_model.dart';
|
||
import 'food_page.dart' show macroDots;
|
||
import 'sugar.dart' show fold;
|
||
|
||
/// Search My foods + the database and pick one (for an ingredient).
|
||
Future<Food?> pickFood(BuildContext context, SyncService sync, FoodDb? fdb) => showModalBottomSheet<Food>(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
backgroundColor: card,
|
||
builder: (_) => _Picker(sync: sync, fdb: fdb),
|
||
);
|
||
|
||
class _Picker extends StatefulWidget {
|
||
const _Picker({required this.sync, required this.fdb});
|
||
final SyncService sync;
|
||
final FoodDb? fdb;
|
||
@override
|
||
State<_Picker> createState() => _PickerState();
|
||
}
|
||
|
||
class _PickerState extends State<_Picker> {
|
||
final q = TextEditingController();
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final t = q.text.trim();
|
||
final my = t.isEmpty ? <Food>[] : myFoods(widget.sync.store, t);
|
||
final kept = t.isEmpty ? <Food>[] : keptProducts(widget.sync.store, t, fold: fold); // picked from the archive before
|
||
final db = t.isEmpty ? <Food>[] : [...kept, ...(widget.fdb?.search(t, limit: 12) ?? []).where((f) => !kept.any((k) => k.foodId == f.foodId))];
|
||
Widget tile(Food f) => ListTile(
|
||
dense: true,
|
||
contentPadding: EdgeInsets.zero,
|
||
title: Text(f.name),
|
||
subtitle: Text([
|
||
if (f.kind == 'my') f.isMeal ? 'My meal' : 'My food' else if (f.kind == 'off') f.brand ?? 'product' else f.category,
|
||
'${(f.per100['kcal'] ?? 0).round()} kcal / 100 g',
|
||
].join(' · '), style: const TextStyle(color: muted)),
|
||
onTap: () => Navigator.pop(context, f),
|
||
);
|
||
return Padding(
|
||
padding: EdgeInsets.fromLTRB(16, 14, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
|
||
child: ConstrainedBox(
|
||
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
|
||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
const Text('Add an ingredient', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||
TextField(controller: q, autofocus: true, onChanged: (_) => setState(() {}),
|
||
decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Search foods…')),
|
||
Flexible(child: ListView(shrinkWrap: true, children: [
|
||
if (my.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('My foods', style: TextStyle(color: muted, fontSize: 12.5))),
|
||
...my.map(tile),
|
||
if (db.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('Food database · products', style: TextStyle(color: muted, fontSize: 12.5))),
|
||
...db.map(tile),
|
||
])),
|
||
]),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// The day's entries to tick for a meal → (picked entries) or null; "from scratch" = [].
|
||
Future<List<Entry>?> pickEntries(BuildContext context, List<Entry> es) => showModalBottomSheet<List<Entry>>(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
backgroundColor: card,
|
||
builder: (_) => _EntryPicker(es),
|
||
);
|
||
|
||
class _EntryPicker extends StatefulWidget {
|
||
const _EntryPicker(this.es);
|
||
final List<Entry> es;
|
||
@override
|
||
State<_EntryPicker> createState() => _EntryPickerState();
|
||
}
|
||
|
||
class _EntryPickerState extends State<_EntryPicker> {
|
||
final picked = <String>{};
|
||
|
||
@override
|
||
Widget build(BuildContext context) => Padding(
|
||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
|
||
child: ConstrainedBox(
|
||
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75),
|
||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
const Text('Make a meal', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||
const Text('Tick what went into it — or start from scratch.', style: TextStyle(color: muted)),
|
||
Flexible(child: ListView(shrinkWrap: true, children: [
|
||
for (final e in widget.es)
|
||
CheckboxListTile(
|
||
dense: true,
|
||
contentPadding: EdgeInsets.zero,
|
||
value: picked.contains(e.u),
|
||
onChanged: (x) => setState(() => x! ? picked.add(e.u) : picked.remove(e.u)),
|
||
title: Text(e.name),
|
||
subtitle: Text('${mealLabels[e.meal]} · ${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal',
|
||
style: const TextStyle(color: muted)),
|
||
),
|
||
])),
|
||
Row(children: [
|
||
TextButton(onPressed: () => Navigator.pop(context, <Entry>[]), child: const Text('Start from scratch')),
|
||
const Spacer(),
|
||
FilledButton(
|
||
onPressed: picked.isEmpty ? null : () => Navigator.pop(context, widget.es.where((e) => picked.contains(e.u)).toList()),
|
||
child: Text('Next (${picked.length})'),
|
||
),
|
||
]),
|
||
]),
|
||
),
|
||
);
|
||
}
|
||
|
||
class MealBuilder extends StatefulWidget {
|
||
/// [row] = the meal being edited; [fromEntries] = entries to build it from (they may be replaced).
|
||
const MealBuilder({super.key, required this.sync, required this.fdb, this.row, this.fromEntries = const []});
|
||
final SyncService sync;
|
||
final FoodDb? fdb;
|
||
final Map<String, dynamic>? row;
|
||
final List<Entry> fromEntries;
|
||
@override
|
||
State<MealBuilder> createState() => _MealBuilderState();
|
||
}
|
||
|
||
class _MealBuilderState extends State<MealBuilder> {
|
||
late final name = TextEditingController(text: widget.row?['name'] as String? ?? '');
|
||
late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
|
||
late final done = TextEditingController(
|
||
text: widget.row == null || doneGramsOf(widget.row!) == null ? '' : num1(doneGramsOf(widget.row!)!));
|
||
late final List<Ingredient> ings = widget.row != null
|
||
? recipeOf(widget.sync.store, widget.fdb, widget.row!)
|
||
: [for (final e in widget.fromEntries) _fromEntry(e)];
|
||
late final amounts = [for (final i in ings) TextEditingController(text: i.amount == null ? '' : num1(i.amount!))];
|
||
late final portions = [
|
||
for (final p in (widget.row == null ? <Portion>[] : myFood(widget.row!).portions).where((p) => p.label != 'whole meal'))
|
||
(TextEditingController(text: p.label), TextEditingController(text: num1(p.grams)))
|
||
];
|
||
bool together = true, armed = false;
|
||
String? error;
|
||
|
||
Ingredient _fromEntry(Entry e) {
|
||
final f = foodOf(widget.sync.store, widget.fdb, e);
|
||
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) return Ingredient.food(f, e.amount, e.unit);
|
||
// its grams when known — an amount in g / ml is its weight
|
||
final g = e.n('grams') ?? (e.amount != null && (e.unit == 'g' || e.unit == 'ml') ? e.amount : null);
|
||
return Ingredient.fixed({for (final c in foodCols) c: e.n(c)}, e.name, e.amount, e.unit, g);
|
||
}
|
||
|
||
double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.'));
|
||
|
||
Future<void> _add() async {
|
||
final f = await pickFood(context, widget.sync, widget.fdb);
|
||
if (f == null) return;
|
||
setState(() {
|
||
final unit = f.portions.isNotEmpty ? f.portions.first.label : 'g';
|
||
ings.add(Ingredient.food(f, unit == 'g' ? 100 : 1, unit));
|
||
amounts.add(TextEditingController(text: unit == 'g' ? '100' : '1'));
|
||
});
|
||
}
|
||
|
||
void _save() {
|
||
for (var i = 0; i < ings.length; i++) {
|
||
ings[i].amount = _n(amounts[i]);
|
||
}
|
||
final ps = [for (final (l, g) in portions) if (l.text.trim().isNotEmpty || g.text.trim().isNotEmpty) Portion(l.text, _n(g) ?? 0)];
|
||
final store = widget.sync.store;
|
||
final (uid, err) = saveMeal(store, uid: widget.row?['_u'] as String?, name: name.text, ings: ings,
|
||
doneGrams: _n(done), portions: ps, note: note.text);
|
||
if (err != null) return setState(() => error = err);
|
||
if (widget.fromEntries.isNotEmpty && together) {
|
||
// one entry of the meal (its whole weight) replaces the picked ones: their day, the most common meal
|
||
final es = widget.fromEntries;
|
||
final counts = <String, int>{};
|
||
for (final e in es) {
|
||
counts[e.meal] = (counts[e.meal] ?? 0) + 1;
|
||
}
|
||
final meal = (counts.entries.toList()..sort((a, b) => b.value.compareTo(a.value))).first.key;
|
||
saveFromFood(store, day: es.first.day, meal: meal.isEmpty ? 'snack' : meal, food: myFoodByUid(store, uid!)!,
|
||
amount: 1, unit: 'whole meal');
|
||
for (final e in es) {
|
||
store.delete('food.entry', e.u);
|
||
}
|
||
}
|
||
widget.sync.changed();
|
||
Navigator.pop(context, uid);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
for (var i = 0; i < ings.length; i++) {
|
||
ings[i].amount = _n(amounts[i]);
|
||
}
|
||
final tot = <String, double>{};
|
||
var grams = 0.0;
|
||
for (final i in ings) {
|
||
i.values.forEach((c, v) {
|
||
if (v != null) tot[c] = (tot[c] ?? 0) + v;
|
||
});
|
||
grams += i.g ?? 0;
|
||
}
|
||
final weight = _n(done) ?? grams;
|
||
return Scaffold(
|
||
appBar: AppBar(title: Text(widget.row == null ? 'New meal' : 'Edit meal')),
|
||
body: ListView(padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [
|
||
TextField(controller: name, decoration: const InputDecoration(labelText: 'Name (e.g. “Cabbage soup (20th Oct 2026)”)')),
|
||
const SizedBox(height: 14),
|
||
Row(children: [
|
||
const Expanded(child: Text('Ingredients', style: TextStyle(fontWeight: FontWeight.bold))),
|
||
TextButton.icon(onPressed: _add, icon: const Icon(Icons.add, size: 18), label: const Text('Ingredient')),
|
||
]),
|
||
for (var i = 0; i < ings.length; i++) _ing(i),
|
||
if (ings.isEmpty) const Text('Nothing yet — + Ingredient.', style: TextStyle(color: muted)),
|
||
const Divider(color: card2, height: 24),
|
||
Row(children: [
|
||
const Text('All together ', style: TextStyle(color: muted)),
|
||
Text('${(tot['kcal'] ?? 0).round()} kcal · ${num1(grams)} g', style: const TextStyle(fontWeight: FontWeight.bold)),
|
||
const SizedBox(width: 8),
|
||
macroDots(tot),
|
||
]),
|
||
TextField(controller: done, keyboardType: const TextInputType.numberWithOptions(decimal: true), onChanged: (_) => setState(() {}),
|
||
decoration: InputDecoration(labelText: 'Weight when done (empty = ${num1(grams)} g)', suffixText: 'g')),
|
||
if (weight > 0)
|
||
Padding(padding: const EdgeInsets.only(top: 6), child: Text(
|
||
'Per 100 g: ${((tot['kcal'] ?? 0) * 100 / weight).round()} kcal · '
|
||
'P ${num1((tot['protein'] ?? 0) * 100 / weight)} · C ${num1((tot['carbs'] ?? 0) * 100 / weight)} · '
|
||
'F ${num1((tot['fat'] ?? 0) * 100 / weight)} g', style: const TextStyle(color: muted))),
|
||
const SizedBox(height: 12),
|
||
Row(children: [
|
||
const Expanded(child: Text('Portions (“whole meal” is added by itself)', style: TextStyle(color: muted, fontSize: 13))),
|
||
TextButton.icon(onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))),
|
||
icon: const Icon(Icons.add, size: 18), label: const Text('Portion')),
|
||
]),
|
||
for (var i = 0; i < portions.length; i++)
|
||
Row(children: [
|
||
Expanded(flex: 3, child: TextField(controller: portions[i].$1, decoration: const InputDecoration(hintText: 'bowl, plate…', isDense: true))),
|
||
const SizedBox(width: 10),
|
||
Expanded(flex: 2, child: TextField(controller: portions[i].$2, keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||
decoration: const InputDecoration(suffixText: 'g', isDense: true))),
|
||
IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)),
|
||
]),
|
||
TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')),
|
||
if (widget.fromEntries.isNotEmpty)
|
||
CheckboxListTile(
|
||
contentPadding: EdgeInsets.zero,
|
||
value: together,
|
||
onChanged: (x) => setState(() => together = x!),
|
||
title: Text('Put the ${widget.fromEntries.length} picked entries together in the diary as one entry'),
|
||
subtitle: const Text('the day’s total stays the same', style: TextStyle(color: muted)),
|
||
),
|
||
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||
const SizedBox(height: 12),
|
||
Row(children: [
|
||
if (widget.row != null)
|
||
TextButton.icon(
|
||
icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad),
|
||
style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null),
|
||
label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)),
|
||
onPressed: () {
|
||
if (!armed) return setState(() => armed = true);
|
||
deleteMyFood(widget.sync.store, widget.row!['_u'] as String);
|
||
widget.sync.changed();
|
||
Navigator.pop(context);
|
||
},
|
||
),
|
||
const Spacer(),
|
||
FilledButton(onPressed: _save, child: const Text('Save')),
|
||
]),
|
||
]),
|
||
);
|
||
}
|
||
|
||
Widget _ing(int i) {
|
||
final ing = ings[i];
|
||
final v = ing.values;
|
||
return Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||
child: Row(children: [
|
||
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||
Text(ing.name, maxLines: 2, overflow: TextOverflow.ellipsis),
|
||
Text(ing.food == null ? 'its own numbers${ing.grams == null ? ' · no weight' : ' · ${num1(ing.grams!)} g'}'
|
||
: '${(v['kcal'] ?? 0).round()} kcal${ing.g == null ? '' : ' · ${num1(ing.g!)} g'}',
|
||
style: const TextStyle(color: muted, fontSize: 12.5)),
|
||
])),
|
||
if (ing.food != null) ...[
|
||
SizedBox(width: 64, child: TextField(controller: amounts[i], keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||
onChanged: (_) => setState(() {}), decoration: const InputDecoration(isDense: true))),
|
||
const SizedBox(width: 8),
|
||
SizedBox(
|
||
width: 110,
|
||
child: DropdownButton<String>(
|
||
value: ing.food!.units.contains(ing.unit) ? ing.unit : 'g',
|
||
isExpanded: true,
|
||
dropdownColor: card2,
|
||
items: [for (final u in ing.food!.units) DropdownMenuItem(value: u, child: Text(u, overflow: TextOverflow.ellipsis))],
|
||
onChanged: (u) => setState(() => ing.unit = u),
|
||
),
|
||
),
|
||
] else
|
||
Text('${(v['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold)),
|
||
IconButton(onPressed: () => setState(() {
|
||
ings.removeAt(i);
|
||
amounts.removeAt(i);
|
||
}), icon: const Icon(Icons.close, size: 18, color: muted)),
|
||
]),
|
||
);
|
||
}
|
||
}
|