calorimeter/lib/enter_food_widget.dart

102 lines
3.1 KiB
Dart

import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kalodings/food_entry_bloc.dart';
import 'package:kalodings/row_with_spacers_widget.dart';
class EnterFoodWidget extends StatefulWidget {
const EnterFoodWidget({
super.key,
});
@override
State<EnterFoodWidget> createState() => _EnterFoodWidgetState();
}
class _EnterFoodWidgetState extends State<EnterFoodWidget> {
String perFoodresult = "dings";
TextEditingController nameController = TextEditingController();
TextEditingController massController = TextEditingController();
TextEditingController kcalPerMassController = TextEditingController();
@override
Widget build(BuildContext context) {
var nameWidget = TextField(
decoration: const InputDecoration(hintText: "Name"),
controller: nameController,
);
var massWidget = TextField(
decoration: const InputDecoration(hintText: "Menge"),
keyboardType: TextInputType.number,
controller: massController,
);
var kcalPerMassWidget = TextField(
decoration: const InputDecoration(hintText: "kcal pro 100g"),
keyboardType: TextInputType.number,
controller: kcalPerMassController);
var enterButton = ElevatedButton(
onPressed: () {
double massAsNumber = 0.0;
double kcalPerMassAsNumber = 0.0;
try {
massAsNumber =
double.parse(massController.text.replaceAll(",", "."));
} catch (e) {
var snackbar =
const SnackBar(content: Text("Menge muss eine Zahl sein"));
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(snackbar);
return;
}
try {
kcalPerMassAsNumber =
double.parse(kcalPerMassController.text.replaceAll(",", "."));
} catch (e) {
var snackbar = const SnackBar(
content: Text("'kcal pro 100g' muss eine Zahl sein"));
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(snackbar);
return;
}
try {
massAsNumber =
double.parse(massController.text.replaceAll(",", "."));
} catch (e) {
var snackbar =
const SnackBar(content: Text("Menge muss eine Zahl sein"));
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(snackbar);
return;
}
var entry = FoodEntry(
name: nameController.text,
mass: massAsNumber,
kcalPerMass: kcalPerMassAsNumber);
log('Entry id: ${entry.id}');
context.read<FoodEntryBloc>().add(FoodEntryEvent(entry: entry));
},
child: const Icon(Icons.add));
return Column(
children: [
RowWidgetWithSpacers(
nameWidget,
massWidget,
kcalPerMassWidget,
null,
enterButton,
),
],
);
}
}