- Saving one of My foods or a meal works every entry logged from it out again for that entry's grams, on any day. Only the entries that change are written, so the rest aren't synced again (db._follow, app _follow). - My foods can have a barcode (8-14 digits, one food per barcode). A scanned or typed barcode finds My foods first (leading zeros ignored), then the food database and kept products; when nothing matches, "New food with barcode" opens the food editor with it filled in. - App 1.1.3 and 1.1.4 changelog entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
239 lines
12 KiB
Dart
239 lines
12 KiB
Dart
// Food ▸ My foods: your own food database (values per 100 g, portions) — the list (tap = edit; a meal
|
||
// opens the meal builder), + New food / New meal, and the food editor sheet (also opened from the add
|
||
// sheet's "+ New food").
|
||
// Delete = hidden (entries made from it keep their numbers), tap twice.
|
||
import 'dart:convert';
|
||
|
||
import 'package:flutter/material.dart';
|
||
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import 'food_archive.dart' show scanBarcode;
|
||
import 'food_model.dart';
|
||
import 'meal_builder.dart';
|
||
|
||
class MyFoodsPage extends StatelessWidget {
|
||
const MyFoodsPage({super.key, required this.sync});
|
||
final SyncService sync;
|
||
|
||
@override
|
||
Widget build(BuildContext context) => Scaffold(
|
||
appBar: AppBar(title: const Text('My foods')),
|
||
floatingActionButton: FloatingActionButton(
|
||
backgroundColor: accent,
|
||
foregroundColor: bg,
|
||
tooltip: 'New food',
|
||
onPressed: () => showModalBottomSheet(
|
||
context: context,
|
||
backgroundColor: card,
|
||
builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||
ListTile(leading: const Icon(Icons.label_outline), title: const Text('New food'),
|
||
subtitle: const Text('from its label', style: TextStyle(color: muted)),
|
||
onTap: () {
|
||
Navigator.pop(c);
|
||
openFoodEditor(context, sync);
|
||
}),
|
||
ListTile(leading: const Icon(Icons.soup_kitchen_outlined), title: const Text('New meal'),
|
||
subtitle: const Text('from its ingredients', style: TextStyle(color: muted)),
|
||
onTap: () async {
|
||
Navigator.pop(c);
|
||
final fdb = await FoodDb.open();
|
||
if (context.mounted) {
|
||
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb)));
|
||
}
|
||
}),
|
||
])),
|
||
),
|
||
child: const Icon(Icons.add),
|
||
),
|
||
body: ListenableBuilder(
|
||
listenable: sync,
|
||
builder: (context, _) {
|
||
final all = allMyFoods(sync.store);
|
||
if (all.isEmpty) {
|
||
return const Center(child: Text('None yet — + to add a food from its label.', style: TextStyle(color: muted)));
|
||
}
|
||
return ListView(padding: const EdgeInsets.fromLTRB(12, 8, 12, 88), children: [
|
||
for (final (r, uses) in all)
|
||
Card(
|
||
margin: const EdgeInsets.only(bottom: 8),
|
||
child: ListTile(
|
||
title: Text(r['name'] as String),
|
||
subtitle: Text([
|
||
'${((r['kcal'] as num?) ?? 0).round()} kcal / 100 g',
|
||
if (r['recipe'] != null) 'meal',
|
||
...((jsonDecode((r['portions'] as String?) ?? '[]') as List).map((p) => '${p['label']} ${num1((p['grams'] as num).toDouble())} g')),
|
||
if (uses > 0) 'used $uses×',
|
||
].join(' · '), style: const TextStyle(color: muted)),
|
||
onTap: () async {
|
||
if (r['recipe'] == null) {
|
||
await openFoodEditor(context, sync, row: r);
|
||
return;
|
||
}
|
||
final fdb = await FoodDb.open();
|
||
if (context.mounted) {
|
||
Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb, row: r)));
|
||
}
|
||
},
|
||
),
|
||
),
|
||
]);
|
||
},
|
||
),
|
||
);
|
||
}
|
||
|
||
/// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted). [barcode]: a new food's,
|
||
/// from a scan / typed barcode nothing was found for.
|
||
Future<String?> openFoodEditor(BuildContext context, SyncService sync, {Map<String, dynamic>? row, String name = '', String barcode = ''}) =>
|
||
showModalBottomSheet<String>(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
backgroundColor: card,
|
||
builder: (_) => FoodEditor(sync: sync, row: row, name: name, barcode: barcode),
|
||
);
|
||
|
||
class FoodEditor extends StatefulWidget {
|
||
const FoodEditor({super.key, required this.sync, this.row, this.name = '', this.barcode = ''});
|
||
final SyncService sync;
|
||
final Map<String, dynamic>? row;
|
||
final String name, barcode;
|
||
@override
|
||
State<FoodEditor> createState() => _FoodEditorState();
|
||
}
|
||
|
||
class _FoodEditorState extends State<FoodEditor> {
|
||
late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name);
|
||
late final note = TextEditingController(text: widget.row?['note'] as String? ?? '');
|
||
late final barcode = TextEditingController(text: widget.row?['barcode'] as String? ?? widget.barcode);
|
||
late String sugarKind = widget.row?['sugar_kind'] as String? ?? ''; // '' = estimated (sugar.dart)
|
||
late final values = {
|
||
for (final k in foodFields.keys)
|
||
k: TextEditingController(text: widget.row?[k] == null ? '' : num1((widget.row![k] as num).toDouble()))
|
||
};
|
||
late final portions = [
|
||
for (final p in (jsonDecode((widget.row?['portions'] as String?) ?? '[]') as List).cast<Map<String, dynamic>>())
|
||
(TextEditingController(text: p['label'] as String), TextEditingController(text: num1((p['grams'] as num).toDouble())))
|
||
];
|
||
String? error;
|
||
bool armed = false;
|
||
|
||
bool get isMeal => widget.row?['recipe'] != null;
|
||
|
||
double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.'));
|
||
|
||
void _save() {
|
||
final ps = <Portion>[];
|
||
for (final (l, g) in portions) {
|
||
if (l.text.trim().isEmpty && g.text.trim().isEmpty) continue;
|
||
ps.add(Portion(l.text, _n(g) ?? 0));
|
||
}
|
||
final (uid, err) = saveMyFood(widget.sync.store, uid: widget.row?['_u'] as String?, name: name.text,
|
||
per100: isMeal ? {for (final k in foodFields.keys) k: (widget.row![k] as num?)?.toDouble()} : {for (final e in values.entries) e.key: _n(e.value)},
|
||
portions: ps, note: note.text, sugarKind: sugarKind, barcode: barcode.text);
|
||
if (err != null) return setState(() => error = err);
|
||
widget.sync.changed();
|
||
Navigator.pop(context, uid);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) => Padding(
|
||
padding: EdgeInsets.fromLTRB(16, 16, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
|
||
child: SingleChildScrollView(
|
||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Text(widget.row == null ? 'New food' : isMeal ? 'Meal' : 'Edit food',
|
||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||
TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty,
|
||
decoration: const InputDecoration(labelText: 'Name')),
|
||
if (!isMeal)
|
||
TextField(
|
||
controller: barcode,
|
||
keyboardType: TextInputType.number,
|
||
decoration: InputDecoration(
|
||
labelText: 'Barcode',
|
||
hintText: 'optional — scanning it finds this food',
|
||
suffixIcon: IconButton(
|
||
tooltip: 'Scan a barcode',
|
||
icon: const Icon(Icons.qr_code_scanner),
|
||
onPressed: () async {
|
||
final code = await scanBarcode(context);
|
||
if (code != null && mounted) setState(() => barcode.text = code);
|
||
},
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(height: 10),
|
||
Text(isMeal ? 'Per 100 g — from its ingredients (change them with the meal builder)' : 'Per 100 g (from the label)',
|
||
style: const TextStyle(color: muted, fontSize: 13)),
|
||
GridView.count(
|
||
crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||
crossAxisSpacing: 12, childAspectRatio: 3.2,
|
||
children: [
|
||
for (final e in foodFields.entries)
|
||
TextField(
|
||
controller: values[e.key],
|
||
enabled: !isMeal,
|
||
autofocus: widget.row == null && widget.name.isNotEmpty && e.key == 'kcal',
|
||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||
textInputAction: TextInputAction.next,
|
||
decoration: InputDecoration(labelText: e.value.$1, suffixText: e.value.$2),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 10),
|
||
Row(children: [
|
||
const Expanded(child: Text('Portions', 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: 'slice, pot, bowl…', 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')),
|
||
// when the added-sugar estimate gets this one wrong (homemade jam, unsweetened yogurt …)
|
||
Row(children: [
|
||
const Expanded(child: Text('Sugar counts as', style: TextStyle(color: muted))),
|
||
DropdownButton<String>(
|
||
value: sugarKind,
|
||
underline: const SizedBox(),
|
||
dropdownColor: card2,
|
||
items: const [
|
||
DropdownMenuItem(value: '', child: Text('estimated')),
|
||
DropdownMenuItem(value: 'added', child: Text('all added')),
|
||
DropdownMenuItem(value: 'dairy', child: Text('milk\'s own, beyond it added')),
|
||
DropdownMenuItem(value: 'natural', child: Text('natural (none added)')),
|
||
],
|
||
onChanged: (v) => setState(() => sugarKind = v ?? ''),
|
||
),
|
||
]),
|
||
if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))),
|
||
const SizedBox(height: 10),
|
||
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')),
|
||
]),
|
||
]),
|
||
),
|
||
);
|
||
}
|