How to change dynamically a initialValue in Flutter

倾然丶 夕夏残阳落幕 提交于 2020-01-16 19:39:10

问题


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.

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.

What I'm doing wrong?


回答1:


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;
    });
  }


来源:https://stackoverflow.com/questions/56100736/how-to-change-dynamically-a-initialvalue-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!