Flutter how to display datepicker when textformfield is clicked

Viewed 52553
new TextFormField(
    decoration: new InputDecoration(hintText: 'DOB'),
    maxLength: 10,
    validator: validateDob,
    onSaved: (String val) {
        strDob = val;
    },
),

Future _selectDate() async {
    DateTime picked = await showDatePicker(
        context: context,
        initialDate: new DateTime.now(),
        firstDate: new DateTime(2016),
        lastDate: new DateTime(2019)
    );
    if(picked != null) setState(() => _value = picked.toString());
}

I created one textFormField when i click the field i want to display datepicker then i have to select one date from the picker after selecting the date i want to set the selected date in the textFormField.

8 Answers

Update 2020:

As pointed by another answer @Lekr0 this can now be done using onTap() property of TextFormField.

TextFormField(
      onTap: (){
        // Below line stops keyboard from appearing
        FocusScope.of(context).requestFocus(new FocusNode());

        // Show Date Picker Here

      },
    )

Original Answer:

Simple Way of Doing it :

Wrap your TextFormField with IgnorePointer & wrap IgnorePointer with InkWell

InkWell(
        onTap: () {
          _selectDate();   // Call Function that has showDatePicker()
        },
        child: IgnorePointer(
          child: new TextFormField(
            decoration: new InputDecoration(hintText: 'DOB'),
            maxLength: 10,
            // validator: validateDob,
            onSaved: (String val) {},
          ),
        ),
      ),

Also in Your _selectDate() make lastDate: new DateTime(2020)); else you will get error.

TextEditingController dateCtl = TextEditingController();

TextFormField(
       controller: dateCtl,
       decoration: InputDecoration(
       labelText: "Date of birth",
       hintText: "Ex. Insert your dob",), 
       onTap: () async{
DateTime date = DateTime(1900);
FocusScope.of(context).requestFocus(new FocusNode());

date = await showDatePicker(
              context: context, 
              initialDate:DateTime.now(),
              firstDate:DateTime(1900),
              lastDate: DateTime(2100));

dateCtl.text = date.toIso8601String();},)

You can use OnTap property to achieve this

TextFormField(
      onTap: (){
        // Below line stops keyboard from appearing
        FocusScope.of(context).requestFocus(new FocusNode());

        // Show Date Picker Here

      },
    )

To stop keyboard from appearing, you can set the readOnly property of the TextFormField to true.

TextFormField(
  readOnly: true,
  ...
);

I don't know why you want to display DatePicker on click of TextFormField?

BTW you have to set enabled=false property of TextFormField and warp TextFormField to GestureDetector that has onTap property where you can call your DatePicker Method.

TextEditingController intialdateval = TextEditingController();


Future _selectDate() async {
   DateTime picked = await showDatePicker(
       context: context,
       initialDate: new DateTime.now(),
       firstDate: new DateTime(2020),
       lastDate: new DateTime(2030));
   if (picked != null)
     setState(
       () => { data.registrationdate = picked.toString(),
       intialdateval.text = picked.toString()
       }
     );
 }
TextFormField(
             // focusNode: _focusNode,
             keyboardType: TextInputType.phone,
             autocorrect: false,
             controller: intialdateval,
             onSaved: (value) {
               data.registrationdate = value;
             },
             onTap: () {
               _selectDate();
               FocusScope.of(context).requestFocus(new FocusNode());
             },

             maxLines: 1,
             //initialValue: 'Aseem Wangoo',
             validator: (value) {
               if (value.isEmpty || value.length < 1) {
                 return 'Choose Date';
               }
             },
             decoration: InputDecoration(
               labelText: 'Registration Date.',
               //filled: true,
               icon: const Icon(Icons.calendar_today),
               labelStyle:
                   TextStyle(decorationStyle: TextDecorationStyle.solid),
             ),
           ),

final _dateController = useTextEditingController();

TextFormField(
  readOnly: true,
  controller: _dateController,
  decoration: InputDecoration(
    labelText: 'Date',
  ),
  onTap: () async {
    await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2015),
      lastDate: DateTime(2025),
    ).then((selectedDate) {
      if (selectedDate != null) {
        _dateController.text =
            DateFormat('yyyy-MM-dd').format(selectedDate);
      }
    });
  },
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Please enter date.';
    }
    return null;
  },
)

Try this!

GestureDetector(
                        onTap: () {
                          var tm = showCupertinoDatePicker(
                              firstDate:
                                  defaultDateTime.add(Duration(days: -1)),
                              lastDate: defaultDateTime.add(Duration(days: 1)),
                              context: context,
                              initialDate: newDate);
                          tm.then((selectedDate) {
                            if (selectedDate != null) {
                              setState(() {
                                newDate = selectedDate;
                              });
                              dateController.text =
                                  "${DateTimeUtils.formatDate(newDate)}";
                            }
                          });
                        },
                        child: AbsorbPointer(
                          child: TextFormField(
                              controller: dateController,
                              autofocus: false,
                              validator: ((val) {
                                if (val.trim().isEmpty) {
                                  return “Select Date";
                                }
                                return null;
                              }),
                              decoration: InputDecoration(
                                  icon: Icon(Icons.today),
                                  suffix: Text("Tap to change",
                                      style: Theme.of(context)
                                          .textTheme
                                          .caption))),
                        ),
                      ),

I'm using all place comman widget

Related