import 'package:flutter/material.dart'; import 'package:fooder/screens/based.dart'; import 'package:fooder/models/diary.dart'; import 'package:fooder/models/preset.dart'; import 'package:fooder/widgets/preset.dart'; import 'package:fooder/components/text.dart'; import 'package:fooder/components/floating_action_button.dart'; class AddMealScreen extends BasedScreen { final Diary diary; const AddMealScreen({super.key, required super.ctx, required this.diary}); @override State createState() => _AddMealScreen(); } class _AddMealScreen extends BasedState { final nameController = TextEditingController(); final presetNameController = TextEditingController(); bool nameChanged = false; List presets = []; Preset? selectedPreset; Diary get diary => widget.diary; Future _getPresets() async { var presets = await client.preset.list(presetNameController.text); setState(() { this.presets = presets; selectedPreset = null; }); } @override void initState() { super.initState(); setState(() { nameController.text = "Meal ${diary.meals.length + 1}"; }); _getPresets(); } @override void dispose() { nameController.dispose(); super.dispose(); } void popMeDaddy() { Navigator.pop( context, ); } Future addMeal() async { await client.meal.create( name: nameController.text, diaryId: diary.id, ); popMeDaddy(); } Future deletePreset(Preset preset) async { client.preset.delete(preset.id); setState(() { presets.remove(preset); }); } Future deletePresetPopup(context, Preset preset) async { showDialog( context: context, builder: (context) { return AlertDialog( title: const Text('Confirm deletion of the preset'), actions: [ IconButton( icon: const Icon(Icons.cancel), onPressed: () { Navigator.pop(context); }, ), IconButton( icon: const Icon(Icons.delete), onPressed: () { deletePreset(preset); Navigator.pop(context); }, ), ], ); }, ); } Future addMealFromPreset() async { if (selectedPreset == null) { addMeal(); return; } await client.meal.createFromPreset( name: nameChanged ? nameController.text : selectedPreset!.name, diaryId: diary.id, presetId: selectedPreset!.id, ); popMeDaddy(); } @override Widget build(BuildContext context) { return Scaffold( appBar: appBar(), body: Center( child: Container( constraints: const BoxConstraints(maxWidth: 720), padding: const EdgeInsets.all(10), child: ListView(children: [ FTextInput( labelText: 'Meal name', controller: nameController, onChanged: (_) => setState(() { nameChanged = true; }), ), FTextInput( labelText: 'Search presets', controller: presetNameController, onChanged: (_) => _getPresets(), ), for (var preset in presets) ListTile( onTap: () { setState(() { presets = [preset]; presetNameController.text = preset.name; selectedPreset = preset; }); addMealFromPreset(); }, onLongPress: () { deletePresetPopup(context, preset); }, title: PresetWidget( preset: preset, ), ), ]), ), ), floatingActionButton: FActionButton( onPressed: addMealFromPreset, icon: Icons.playlist_add_rounded, ), ); } }