如何在Flutter中动态更改initialValue [英] How to change dynamically a initialValue in Flutter
问题描述
我有一个包含一些字段的表单,其中一个是日期字段:
I have a Form that contains some fields, one of them is a date field:
GestureDetector(
onTap: () {
selectDate(context);
},
child: AbsorbPointer(
child: TextFormField(
initialValue: dataEvento,
decoration: InputDecoration(
labelText: 'Date ${dataEvento}',
labelStyle: TextStyle(
fontFamily: 'acumin-pro',
fontSize:
MediaQuery.of(context).size.height * 0.022,
fontWeight: FontWeight.bold,
color: Colors.grey),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: dataUserGlobal.yellow))),
style: TextStyle(color: dataUserGlobal.lightBlue),
validator: (value) =>
value.isEmpty ? 'Campo obbligatorio' : null,
onSaved: (value) => dataEvento = value,
),
),
),
当我点击该字段时,我会调用此函数
When I tap on that field I call this function
DateTime selectedDate = DateTime.now();
Future selectDate(BuildContext context) async {
DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101));
if (picked != null && picked != selectedDate)
setState(() {
dataEvento = DateFormat('yyyy-MM-dd').format(picked);
});
}
但我无法更改字段内的值。
but I can't change the value inside the field.
要进行调试,我尝试在标签文本 labelText:'Date $ {dataEvento}'
中插入变量名称当我单击该字段并选择日期时,它会显示日期。
但是字段 initialValue
仍然为空。
For debugging it I try to insert the name of the variable inside my label text labelText: 'Date ${dataEvento}'
and this shows me the date when I click on the field and chose the date.
But the field initialValue
remains blank.
我在做什么错了?
推荐答案
向这样的textFormField添加控制器的方法如下:
What about adding a controller to your textFormField like this :
TextEditingController _txtFormCtrl = TextEditingController();
,此功能可以为您提供帮助:
, and this is a function that can help you :
void _changeDatetime(int year, int month, int date) {
setState(() {
_year = year;
_month = month;
_date = date;
_datetime = '$year-$month-$date';
_txtFormCtrl.text = _datetime;
});
}
这篇关于如何在Flutter中动态更改initialValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!