I want to make a form so the user can input the date and time of his appointment. I tried some options but only the date works(it shows the user's input) but the time remains empty even though the TimePicker appears and he can select the time he wants. How can I fix this?
TextEditingController dateCtl = TextEditingController();
class MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
DateTime date = DateTime.now();
@override
Widget build(BuildContext context) {
String _formattedate = new DateFormat.yMMMMEEEEd().format(date);
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
child: TextFormField(
controller: dateCtl,
decoration: InputDecoration(labelText: 'Date*'),
onTap: () async {
FocusScope.of(context).requestFocus(new FocusNode());
DateTime picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime(2021));
dateCtl.text = _formattedate.toString();
if(picked != null && picked != date){
setState(() {
date = picked;
});
}
},
validator: (value) {
if (value.isEmpty) {
return 'cant be empty';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
child: TextFormField(
decoration: InputDecoration(
labelText: 'time*',
),
onTap: () async {
TimeOfDay time = TimeOfDay.now();
FocusScope.of(context).requestFocus(new FocusNode());
TimeOfDay picked =
await showTimePicker(context: context, initialTime: time);
if (picked != null && picked != time)
setState(() {
time = picked;
});
},
validator: (value) {
if (value.isEmpty) {
return 'cant be empty';
}
return null;
},
),
),
//more code
Add this line under the dateCtl.
TextEditingController timeCtl = TextEditingController();
And add 2 lines.
child: TextFormField(
controller: timeCtl, // add this line.
decoration: InputDecoration(
labelText: 'time*',
),
onTap: () async {
TimeOfDay time = TimeOfDay.now();
FocusScope.of(context).requestFocus(new FocusNode());
TimeOfDay picked =
await showTimePicker(context: context, initialTime: time);
if (picked != null && picked != time) {
timeCtl.text = picked.toString(); // add this line.
setState(() {
time = picked;
});
}
},
validator: (value) {
if (value.isEmpty) {
return 'cant be empty';
}
return null;
},
),
format ex 1
timeCtl.text = picked.format(context);
ex 2
var now = DateTime.now();
var dt = DateTime(now.year, now.month, now.day, picked.hour, picked.minute);
String _formattetime = DateFormat.Hm().format(dt);
timeCtl.text = _formattetime;