diameter/lib/screens/meal/meal_category_detail.dart

123 lines
3.6 KiB
Dart

import 'package:diameter/components/detail.dart';
import 'package:diameter/components/dialogs.dart';
import 'package:diameter/components/forms.dart';
import 'package:diameter/config.dart';
import 'package:diameter/navigation.dart';
import 'package:flutter/material.dart';
import 'package:diameter/models/meal_category.dart';
class MealCategoryDetailScreen extends StatefulWidget {
static const String routeName = '/meal-category';
final int id;
const MealCategoryDetailScreen({Key? key, this.id = 0}) : super(key: key);
@override
_MealCategoryDetailScreenState createState() =>
_MealCategoryDetailScreenState();
}
class _MealCategoryDetailScreenState extends State<MealCategoryDetailScreen> {
MealCategory? _mealCategory;
bool _isNew = true;
final GlobalKey<FormState> _mealCategoryForm = GlobalKey<FormState>();
final _valueController = TextEditingController(text: '');
final _notesController = TextEditingController(text: '');
@override
void initState() {
super.initState();
reload();
if (_mealCategory != null) {
_valueController.text = _mealCategory!.value;
_notesController.text = _mealCategory!.notes ?? '';
}
}
void reload() {
if (widget.id != 0) {
setState(() {
_mealCategory = MealCategory.get(widget.id);
});
}
_isNew = _mealCategory == null;
}
void handleSaveAction() async {
if (_mealCategoryForm.currentState!.validate()) {
MealCategory.put(MealCategory(
id: widget.id,
value: _valueController.text,
notes: _notesController.text));
Navigator.pop(context, '${_isNew ? 'New' : ''} Meal Category saved');
}
}
void handleCancelAction() {
if (showConfirmationDialogOnCancel &&
(_isNew &&
(_valueController.text != '' || _notesController.text != '')) ||
(!_isNew &&
(_mealCategory!.value != _valueController.text ||
(_mealCategory!.notes ?? '') != _notesController.text))) {
Dialogs.showCancelConfirmationDialog(
context: context,
isNew: _isNew,
onSave: handleSaveAction,
);
} else {
Navigator.pop(context);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_isNew ? 'New Meal Category' : _mealCategory!.value),
),
drawer:
const Navigation(currentLocation: MealCategoryDetailScreen.routeName),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
FormWrapper(
formState: _mealCategoryForm,
fields: [
TextFormField(
controller: _valueController,
decoration: const InputDecoration(
labelText: 'Name',
),
validator: (value) {
if (value!.trim().isEmpty) {
return 'Empty name';
}
return null;
},
),
TextFormField(
controller: _notesController,
decoration: const InputDecoration(
labelText: 'Notes',
alignLabelWithHint: true,
),
keyboardType: TextInputType.multiline,
),
],
),
],
),
),
bottomNavigationBar: DetailBottomRow(
onCancel: handleCancelAction,
onSave: handleSaveAction,
),
);
}
}