import 'package:cdb_ui/api.dart'; import 'package:flutter/material.dart'; class ConsumePage extends StatefulWidget { final String item; final String variant; final String transaction; final Function refresh; const ConsumePage(this.transaction, this.item, this.variant, this.refresh, {super.key}); @override State createState() => _ConsumePageState(); } class _ConsumePageState extends State { final _formKey = GlobalKey(); String _selectedDestination = ""; String _price = ""; @override void initState() { super.initState(); } void _consume() { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); API() .consumeItem(widget.transaction, _selectedDestination, "$_price €") .then((_) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Item consumed successfully!')), ); Navigator.of(context).pop(); widget.refresh(); }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Consume Item'), ), body: FutureBuilder( future: API().getUniqueField(widget.item, widget.variant, "destination"), builder: (context, snapshot) { if (!snapshot.hasData) { return const Center(child: CircularProgressIndicator()); } var destinations = snapshot.data!; return Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Destination Field with Dropdown and Text Input Autocomplete( optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text.isEmpty) { return destinations; } return destinations.where((String option) { return option .toLowerCase() .contains(textEditingValue.text.toLowerCase()); }); }, onSelected: (String selection) { setState(() { _selectedDestination = selection; }); }, fieldViewBuilder: (context, textEditingController, focusNode, onFieldSubmitted) { textEditingController.text = _selectedDestination; return TextFormField( onChanged: (value) { _selectedDestination = value; }, controller: textEditingController, focusNode: focusNode, decoration: const InputDecoration( labelText: 'Destination', border: OutlineInputBorder(), ), validator: (value) { if (value?.isEmpty ?? true) { return "Please enter a destination"; } return null; }, ); }, ), const SizedBox(height: 16), // Price Field TextFormField( decoration: const InputDecoration(labelText: 'Price'), keyboardType: TextInputType.number, initialValue: _price, validator: (value) { if (value == null || value.isEmpty) { return 'Please enter a price'; } if (double.tryParse(value) == null) { return 'Please enter a valid number'; } return null; }, onSaved: (value) { _price = value!; }, ), const SizedBox(height: 20), // Submit Button ElevatedButton( onPressed: _consume, child: const Text('Consume Item'), ), ], ), ), ); }, ), ); } }