import 'package:flutter/material.dart'; class AddLocationsForm extends StatefulWidget { final Function saveNewLocation; final List savedLocations; const AddLocationsForm( {Key? key, required this.saveNewLocation, required this.savedLocations}) : super(key: key); @override AddLocationsFormState createState() => AddLocationsFormState(); } class AddLocationsFormState extends State { final _formKey = GlobalKey(); final locationFormController = TextEditingController(); String? newLocationName; double? newLatitude; double? newLongitude; @override void initState() { super.initState(); } @override void dispose() { locationFormController.dispose(); super.dispose(); } void _submitLocation() { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); widget.saveNewLocation(newLocationName!, newLatitude!, newLongitude!); _formKey.currentState!.reset(); newLocationName = null; newLatitude = null; newLongitude = null; } } @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column(children: [ Flexible( flex: 4, child: TextFormField( //Location Name onSaved: (input) { newLocationName = input; }, controller: locationFormController, validator: ((value) { if (value == null || value.isEmpty) { return "Please enter a name for the new location"; } if (widget.savedLocations.contains(value)) { return "Location name already in use"; } return null; }), decoration: const InputDecoration( border: UnderlineInputBorder(), labelText: "Location Name"), )), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Flexible( flex: 1, child: TextFormField( //Latitude validator: ((value) { if (value == null || value.isEmpty) { return "Please enter a value"; } try { double.parse(value); } catch (e) { return "Please enter a number"; } return null; }), onSaved: (input) { newLatitude = double.parse(input!); }, keyboardType: TextInputType.number, decoration: const InputDecoration( border: UnderlineInputBorder(), labelText: "Latitude"), )), const SizedBox(width: 10), Flexible( flex: 1, child: TextFormField( //Longitude validator: ((value) { if (value == null || value.isEmpty) { return "Please enter a value"; } try { double.parse(value); } catch (e) { return "Please enter a number"; } return null; }), onSaved: (input) { newLongitude = double.parse(input!); }, keyboardType: TextInputType.number, decoration: const InputDecoration( border: UnderlineInputBorder(), labelText: "Longitude"), )), const SizedBox(width: 10), Flexible( flex: 2, child: ElevatedButton( onPressed: () { _submitLocation(); }, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: const [ Icon(Icons.add), SizedBox(width: 5), Text("Add Location") ], ))) ], ) ])); } }