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>
420 lines
19 KiB
Dart
420 lines
19 KiB
Dart
// Adding / editing a food entry (the web page's inline editor as a bottom sheet, lifted by the
|
||
// keyboard). Modes:
|
||
// search — the box: empty = yesterday's foods (this meal first; + adds one as it was, a tap picks
|
||
// it to change the portion); typed = My foods · Eaten before · Food database · Products
|
||
// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = that
|
||
// product; "Search all products…" = the archive on the sync server (food_archive.dart)
|
||
// food — the picked food: amount + unit (g, ml, its portions, tbsp / tsp), the numbers live, meal
|
||
// totals — an entry without a food (Lifesum imports, estimates): name, kcal / P / C / F
|
||
// Editing an entry opens it in food or totals mode; Delete = tap twice.
|
||
import 'package:flutter/material.dart';
|
||
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import 'cycle_model.dart' show parseDay, plus;
|
||
import 'food_archive.dart';
|
||
import 'food_model.dart';
|
||
import 'food_page.dart' show macroDots;
|
||
import 'my_foods.dart';
|
||
import 'sugar.dart' show fold;
|
||
|
||
class FoodSheet extends StatefulWidget {
|
||
const FoodSheet({super.key, required this.sync, required this.fdb, required this.day, required this.meal, this.entry});
|
||
final SyncService sync;
|
||
final FoodDb? fdb;
|
||
final String day, meal;
|
||
final Entry? entry;
|
||
@override
|
||
State<FoodSheet> createState() => _FoodSheetState();
|
||
}
|
||
|
||
class _FoodSheetState extends State<FoodSheet> {
|
||
late String meal = widget.meal.isEmpty ? 'snack' : widget.meal;
|
||
String mode = 'search';
|
||
final q = TextEditingController();
|
||
Food? food;
|
||
final amount = TextEditingController(), name = TextEditingController(), unitCtl = TextEditingController();
|
||
String unit = 'g';
|
||
final totalsCtl = {for (final k in ['kcal', 'protein', 'carbs', 'fat']) k: TextEditingController()};
|
||
Map<String, dynamic>? copyFrom; // totals mode from an older entry: its other nutrients come along, scaled
|
||
String? error;
|
||
bool armed = false;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
final e = widget.entry;
|
||
if (e != null) {
|
||
final f = foodOf(widget.sync.store, widget.fdb, e);
|
||
if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) {
|
||
_pick(f, e.amount!, e.unit!);
|
||
} else {
|
||
_totals(e);
|
||
}
|
||
}
|
||
}
|
||
|
||
void _pick(Food f, [double? a, String? u]) => setState(() {
|
||
food = f;
|
||
mode = 'food';
|
||
unit = u ?? (f.portions.isNotEmpty ? f.portions.first.label : 'g');
|
||
amount.text = num1(a ?? (unit == 'g' ? 100 : 1));
|
||
error = null;
|
||
});
|
||
|
||
void _totals(Entry e, {bool copy = false}) => setState(() {
|
||
mode = 'totals';
|
||
name.text = e.name;
|
||
amount.text = e.amount == null ? '' : num1(e.amount!);
|
||
unit = e.unit ?? '';
|
||
unitCtl.text = unit;
|
||
for (final k in totalsCtl.keys) {
|
||
totalsCtl[k]!.text = e.n(k) == null ? '' : num1(e.n(k)!);
|
||
}
|
||
copyFrom = copy ? e.row : null;
|
||
error = null;
|
||
});
|
||
|
||
void _done() {
|
||
widget.sync.changed();
|
||
Navigator.pop(context);
|
||
}
|
||
|
||
void _save() {
|
||
final store = widget.sync.store;
|
||
final u = widget.entry?.u;
|
||
String? err;
|
||
if (mode == 'food') {
|
||
final a = double.tryParse(amount.text.trim().replaceAll(',', '.'));
|
||
if (a == null || a <= 0) return setState(() => error = 'How much?');
|
||
err = saveFromFood(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, food: food!, amount: a, unit: unit,
|
||
note: (widget.entry?.row['note'] as String?) ?? '');
|
||
} else {
|
||
double? v(String k) => double.tryParse(totalsCtl[k]!.text.trim().replaceAll(',', '.'));
|
||
err = saveTotals(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, name: name.text,
|
||
values: {for (final k in totalsCtl.keys) k: v(k)},
|
||
amount: double.tryParse(amount.text.trim().replaceAll(',', '.')), unit: unit.isEmpty ? null : unit,
|
||
copyFrom: copyFrom, note: (widget.entry?.row['note'] as String?) ?? '');
|
||
}
|
||
if (err != null) return setState(() => error = err);
|
||
_done();
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final h = MediaQuery.of(context).size.height;
|
||
return Padding(
|
||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||
child: ConstrainedBox(
|
||
constraints: BoxConstraints(maxHeight: h * 0.8),
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
|
||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Row(children: [
|
||
Expanded(child: Text(widget.entry == null ? 'Add to ${mealLabels[meal]!.toLowerCase()}' : 'Edit',
|
||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))),
|
||
DropdownButton<String>(
|
||
value: meal,
|
||
underline: const SizedBox(),
|
||
dropdownColor: card2,
|
||
items: [for (final m in mealKeys) DropdownMenuItem(value: m, child: Text(mealLabels[m]!))],
|
||
onChanged: (m) => setState(() => meal = m!),
|
||
),
|
||
]),
|
||
if (mode == 'search') Flexible(child: _search()) else if (mode == 'food') _foodForm() else _totalsForm(),
|
||
]),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
// ---- search
|
||
Widget _search() {
|
||
final store = widget.sync.store;
|
||
final text = q.text.trim();
|
||
final sections = <(String, List<Widget>)>[];
|
||
if (text.isEmpty) {
|
||
final yday = parseDay(widget.day);
|
||
final ys = entriesOn(store, dayIso(plus(yday, -1))).where((e) => e.meal.isNotEmpty).toList();
|
||
final here = entriesOn(store, widget.day);
|
||
bool already(Entry y) => here.any((e) => e.meal == meal && e.name == y.name && e.amount == y.amount && e.unit == y.unit);
|
||
final mine = ys.where((e) => e.meal == meal).toList(), rest = ys.where((e) => e.meal != meal).toList();
|
||
if (mine.isNotEmpty) sections.add(('Yesterday · ${mealLabels[meal]!.toLowerCase()}', [for (final e in mine) _yday(e, already(e))]));
|
||
if (rest.isNotEmpty) sections.add(('Yesterday · other meals', [for (final e in rest) _yday(e, already(e))]));
|
||
final recent = recentFoods(store, '', limit: 8);
|
||
if (recent.isNotEmpty) sections.add(('Eaten often', [for (final (e, n) in recent) _recent(e, n)]));
|
||
} else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: that product, here or kept
|
||
final found = widget.fdb?.byBarcode(text) ?? keptByBarcode(store, text);
|
||
sections.add(('Barcode $text', [
|
||
for (final f in found) _foodTile(f),
|
||
if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||
child: Text('Not in the food database here — look it up in all products:', style: TextStyle(color: muted))),
|
||
]));
|
||
} else {
|
||
final my = myFoods(store, text);
|
||
final recent = recentFoods(store, text, limit: 5);
|
||
final db = widget.fdb?.search(text, limit: 14) ?? [];
|
||
if (my.isNotEmpty) sections.add(('My foods', [for (final f in my) _foodTile(f)]));
|
||
if (recent.isNotEmpty) sections.add(('Eaten before', [for (final (e, n) in recent) _recent(e, n)]));
|
||
final kept = keptProducts(store, text, fold: fold);
|
||
final usda = db.where((f) => f.kind == 'usda').take(8).toList(),
|
||
off = [...kept, ...db.where((f) => f.kind == 'off' && !kept.any((k) => k.foodId == f.foodId))].take(6).toList();
|
||
if (usda.isNotEmpty) sections.add(('Food database', [for (final f in usda) _foodTile(f)]));
|
||
if (off.isNotEmpty) sections.add(('Products', [for (final f in off) _foodTile(f)]));
|
||
if (widget.fdb == null) sections.add(('', [const Text('Loading the food database…', style: TextStyle(color: muted))]));
|
||
}
|
||
return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
TextField(
|
||
controller: q,
|
||
autofocus: true,
|
||
decoration: InputDecoration(
|
||
prefixIcon: const Icon(Icons.search),
|
||
hintText: 'Search foods…',
|
||
suffixIcon: IconButton(tooltip: 'Scan a barcode', icon: const Icon(Icons.qr_code_scanner), onPressed: _scan),
|
||
),
|
||
onChanged: (_) => setState(() {}),
|
||
),
|
||
const SizedBox(height: 6),
|
||
Flexible(
|
||
child: ListView(shrinkWrap: true, children: [
|
||
for (final (title, items) in sections) ...[
|
||
if (title.isNotEmpty)
|
||
Padding(padding: const EdgeInsets.only(top: 10, bottom: 2),
|
||
child: Text(title, style: const TextStyle(color: muted, fontSize: 12.5, fontWeight: FontWeight.bold))),
|
||
...items,
|
||
],
|
||
if (sections.isEmpty && text.isNotEmpty) const Padding(padding: EdgeInsets.all(12),
|
||
child: Text('Nothing found', style: TextStyle(color: muted))),
|
||
if (text.length >= 3)
|
||
TextButton.icon(
|
||
onPressed: () => _archive(text),
|
||
icon: const Icon(Icons.travel_explore),
|
||
label: Text(RegExp(r'^\d{8,14}$').hasMatch(text) ? 'Look up barcode $text in all products' : 'Search all products for “$text”'),
|
||
),
|
||
if (text.isNotEmpty)
|
||
TextButton.icon(
|
||
onPressed: () async {
|
||
final uid = await openFoodEditor(context, widget.sync, name: text);
|
||
final f = uid == null ? null : myFoodByUid(widget.sync.store, uid);
|
||
if (f != null && mounted) _pick(f);
|
||
},
|
||
icon: const Icon(Icons.add),
|
||
label: Text('New food “$text” (from its label)'),
|
||
),
|
||
if (text.isNotEmpty)
|
||
TextButton.icon(
|
||
onPressed: () => setState(() {
|
||
mode = 'totals';
|
||
name.text = text;
|
||
amount.text = '';
|
||
unit = '';
|
||
unitCtl.text = '';
|
||
copyFrom = null;
|
||
}),
|
||
icon: const Icon(Icons.edit_note),
|
||
label: Text('“$text” with my own numbers'),
|
||
),
|
||
]),
|
||
),
|
||
]);
|
||
}
|
||
|
||
/// The archive (every Open Food Facts product) → the one picked, kept, then as any food.
|
||
Future<void> _archive(String text) async {
|
||
final f = await openArchive(context, widget.sync, widget.fdb, text);
|
||
if (f != null && mounted) _pick(f);
|
||
}
|
||
|
||
/// The camera → a barcode: its product here, else straight to the archive.
|
||
Future<void> _scan() async {
|
||
final code = await scanBarcode(context);
|
||
if (code == null || !mounted) return;
|
||
final here = widget.fdb?.byBarcode(code) ?? keptByBarcode(widget.sync.store, code);
|
||
if (here.length == 1) return _pick(here.first);
|
||
setState(() => q.text = code);
|
||
if (here.isEmpty) await _archive(code);
|
||
}
|
||
|
||
Widget _yday(Entry e, bool done) => ListTile(
|
||
dense: true,
|
||
contentPadding: EdgeInsets.zero,
|
||
title: Text(e.name),
|
||
subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal', style: const TextStyle(color: muted)),
|
||
onTap: () => _fromEntry(e),
|
||
trailing: done
|
||
? const Icon(Icons.check, color: good)
|
||
: IconButton(
|
||
tooltip: 'Add as it was',
|
||
icon: const Icon(Icons.add_circle, color: accent),
|
||
onPressed: () {
|
||
addAgain(widget.sync.store, widget.fdb, e, widget.day, meal);
|
||
widget.sync.changed();
|
||
setState(() {});
|
||
},
|
||
),
|
||
);
|
||
|
||
Widget _recent(Entry e, int n) => ListTile(
|
||
dense: true,
|
||
contentPadding: EdgeInsets.zero,
|
||
title: Text(e.name),
|
||
subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal · $n×', style: const TextStyle(color: muted)),
|
||
onTap: () => _fromEntry(e),
|
||
);
|
||
|
||
/// An older entry picked: its food with its portion, else its numbers (scaled with the amount).
|
||
void _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)) {
|
||
_pick(f, e.amount!, e.unit!);
|
||
} else {
|
||
_totals(e, copy: true);
|
||
}
|
||
}
|
||
|
||
Widget _foodTile(Food f) {
|
||
final k = f.per100['kcal'];
|
||
final sub = [
|
||
if (f.kind == 'off') f.brand ?? '' else if (f.kind != 'my') f.category,
|
||
if (k != null) '${k.round()} kcal / 100 g',
|
||
if (f.isMeal) 'meal',
|
||
].where((x) => x.isNotEmpty).join(' · ');
|
||
return ListTile(
|
||
dense: true,
|
||
contentPadding: EdgeInsets.zero,
|
||
title: Text(f.name),
|
||
subtitle: Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted)),
|
||
trailing: f.nutriscore == null ? null : _score(f.nutriscore!),
|
||
onTap: () => _pick(f),
|
||
);
|
||
}
|
||
|
||
static Widget _score(String s) {
|
||
const colors = {'a': Color(0xFF1E8F4E), 'b': Color(0xFF7AC547), 'c': Color(0xFFF2C40F), 'd': Color(0xFFEE8100), 'e': Color(0xFFE63E11)};
|
||
return Container(
|
||
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
|
||
decoration: BoxDecoration(color: colors[s] ?? card2, borderRadius: BorderRadius.circular(5)),
|
||
child: Text(s.toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
|
||
);
|
||
}
|
||
|
||
// ---- food: amount + unit
|
||
Widget _foodForm() {
|
||
final f = food!;
|
||
final a = double.tryParse(amount.text.trim().replaceAll(',', '.'));
|
||
final g = a == null ? null : f.grams(a, unit);
|
||
final nut = g == null ? null : f.nutrients(g);
|
||
final source = switch (f.kind) {
|
||
'my' => f.isMeal ? 'My meal' : 'My food',
|
||
'off' => 'Product (Open Food Facts)${f.brand != null ? ' · ${f.brand}' : ''}',
|
||
_ => 'Food database (USDA)',
|
||
};
|
||
return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
InkWell(
|
||
onTap: () => setState(() => mode = 'search'),
|
||
child: Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||
child: Row(children: [
|
||
Expanded(child: Text(f.name, style: const TextStyle(fontSize: 16.5, fontWeight: FontWeight.bold))),
|
||
const Icon(Icons.search, color: muted, size: 18),
|
||
]),
|
||
),
|
||
),
|
||
Text(source, style: const TextStyle(color: muted, fontSize: 12.5)),
|
||
const SizedBox(height: 10),
|
||
Row(children: [
|
||
SizedBox(
|
||
width: 100,
|
||
child: TextField(
|
||
controller: amount,
|
||
autofocus: widget.entry == null,
|
||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||
decoration: const InputDecoration(labelText: 'Amount'),
|
||
onChanged: (_) => setState(() {}),
|
||
onSubmitted: (_) => _save(),
|
||
),
|
||
),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: DropdownButtonFormField<String>(
|
||
initialValue: f.units.contains(unit) ? unit : 'g',
|
||
isExpanded: true,
|
||
dropdownColor: card2,
|
||
decoration: const InputDecoration(labelText: 'Unit'),
|
||
items: [
|
||
for (final u in f.units)
|
||
DropdownMenuItem(value: u, child: Text(f.portions.any((p) => p.label == u)
|
||
? '$u (${num1(f.portions.firstWhere((p) => p.label == u).grams)} g)' : u, overflow: TextOverflow.ellipsis)),
|
||
],
|
||
onChanged: (u) => setState(() => unit = u!),
|
||
),
|
||
),
|
||
]),
|
||
const SizedBox(height: 10),
|
||
if (nut != null)
|
||
Row(children: [
|
||
Text('${(nut['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
|
||
Text(' · ${num1(g!)} g · ', style: const TextStyle(color: muted)),
|
||
macroDots(nut),
|
||
]),
|
||
if (nut != null && (nut['fiber'] != null || nut['sugar'] != null))
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 3),
|
||
child: Text([
|
||
if (nut['fiber'] != null) 'fibre ${num1(nut['fiber']!)} g',
|
||
if (nut['sugar'] != null) 'sugar ${num1(nut['sugar']!)} g',
|
||
if (nut['sat_fat'] != null) 'sat. fat ${num1(nut['sat_fat']!)} g',
|
||
if (nut['sodium_mg'] != null) 'sodium ${nut['sodium_mg']!.round()} mg',
|
||
].join(' · '), style: const TextStyle(color: muted, fontSize: 12.5)),
|
||
),
|
||
_actions(),
|
||
]);
|
||
}
|
||
|
||
// ---- totals: an entry without a food
|
||
Widget _totalsForm() => Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
TextField(controller: name, decoration: const InputDecoration(labelText: 'What was it?')),
|
||
Row(children: [
|
||
SizedBox(width: 100, child: TextField(controller: amount, keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||
decoration: const InputDecoration(labelText: 'Amount'))),
|
||
const SizedBox(width: 12),
|
||
Expanded(child: TextField(controller: unitCtl, onChanged: (v) => unit = v.trim(),
|
||
decoration: const InputDecoration(labelText: 'Unit (g, pcs, bowl…)'))),
|
||
]),
|
||
Row(children: [
|
||
for (final (k, l) in [('kcal', 'kcal'), ('protein', 'Protein g'), ('carbs', 'Carbs g'), ('fat', 'Fat g')])
|
||
Expanded(child: Padding(
|
||
padding: const EdgeInsets.only(right: 8),
|
||
child: TextField(controller: totalsCtl[k], keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||
textInputAction: TextInputAction.next, decoration: InputDecoration(labelText: l)),
|
||
)),
|
||
]),
|
||
if (widget.entry != null && widget.entry!.source != 'manual')
|
||
Padding(padding: const EdgeInsets.only(top: 6),
|
||
child: Text('Imported from ${widget.entry!.source} — its other nutrients stay as they are.',
|
||
style: const TextStyle(color: muted, fontSize: 12.5))),
|
||
_actions(),
|
||
]);
|
||
|
||
Widget _actions() => Padding(
|
||
padding: const EdgeInsets.only(top: 12),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
if (error != null) Padding(padding: const EdgeInsets.only(bottom: 6), child: Text(error!, style: const TextStyle(color: bad))),
|
||
Row(children: [
|
||
if (widget.entry != 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);
|
||
widget.sync.store.delete('food.entry', widget.entry!.u);
|
||
_done();
|
||
},
|
||
),
|
||
const Spacer(),
|
||
FilledButton(onPressed: _save, child: Text(widget.entry == null ? 'Add' : 'Save')),
|
||
]),
|
||
]),
|
||
);
|
||
}
|