我想做一个表格,以便用户可以输入约会的日期和时间。 我尝试了一些选项,但是只有日期有效(它显示了用户的输入),但是时间仍然为空,即使出现了TimePicker,他也可以选择所需的时间。我该如何解决?
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
答案 0 :(得分:0)
在dateCtl下添加此行。
TextEditingController timeCtl = TextEditingController();
并添加2行。
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;
},
),
格式为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;