display selected date in a form field for flutter

Issue

I am trying to work out how I can display the selected date back into a formfield for Flutter. If I just use a Text element it works fine

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

Solution

Please try creating a TextEditingController and assign the controller to the TextFormField then set controller.text to the value you want to assign in setState. See the sample code below for reference.

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

Answered By – Solomon Swamynathan

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *