1

我正在尝试弄清楚如何将选定的日期显示回 Flutter 的表单域中。如果我只使用 Text 元素,它可以正常工作

TextFormField(
                          onTap: _selectDate,
                          enabled: true,
                          initialValue: DateFormat("E, d MMM yyyy")
                              .format(_date)
                              .toString(),
                          readOnly: true,
                          decoration: InputDecoration(labelText: 'Date'),
                        ),
                        SizedBox(height: 8),
                        Text(DateFormat("E, d MMM yyyy")
                            .format(_date)
                            .toString()),

void _selectDate() async {
    final DateTime newDate = await showDatePicker(
      context: context,
      initialDate: _date,
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(Duration(days: 90)),
      helpText: 'Select date for task',
    );
    if (newDate != null) {
      setState(() {
        _date = newDate;
      });
    }
  }
4

1 回答 1

0

请尝试创建一个 TextEditingController 并将控制器分配给 TextFormField,然后将 controller.text 设置为您要在 setState 中分配的值。请参阅下面的示例代码以供参考。

TextEditingController _dateController = TextEditingController();

TextFormField(
 controller: _dateController,
                          onTap: _selectDate,
                          enabled: true,
                          initialValue: DateFormat("E, d MMM yyyy")
                              .format(_date)
                              .toString(),
                          readOnly: true,
                          decoration: InputDecoration(labelText: 'Date'),
                        ),
                        SizedBox(height: 8),
                        Text(DateFormat("E, d MMM yyyy")
                            .format(_date)
                            .toString()),

void _selectDate() async {
    final DateTime newDate = await showDatePicker(
      context: context,
      initialDate: _date,
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(Duration(days: 90)),
      helpText: 'Select date for task',
    );
    if (newDate != null) {
      setState(() {
        _date = newDate;
_dateController.text = _date.toString();
      });
    }
  }
于 2021-07-21T13:22:29.870 回答