Rajath
Rajath

Reputation: 2971

How to set the default date for the Date picker in flutter?

Below code is working properl. But I don't know how to set the default date value!

final dateFormat = DateFormat("dd-M-yyyy");

DateTimePickerFormField(
    dateOnly: true,
    format: dateFormat,
    decoration: InputDecoration(labelText: 'Select Date'),
    initialDate: DateTime.now(),
    onSaved: (value){
        _date = value;
    },
),

I'm using datetime_picker_formfield: flutter library.

I'm trying to do that with initialDate: DateTime.now() initial date property but it was not displaying anything as an initial value.

Thanks in advance!

Upvotes: 6

Views: 34898

Answers (2)

George
George

Reputation: 357

Change onSaved: to onChanged: and add setState

onChanged: (selectedDate) {
    setState(() {
      _properties.gameDateTime = selectedDate;
    });
  },

Upvotes: 0

anmol.majhail
anmol.majhail

Reputation: 51176

In Order to show the initial date Value you need to Use - initialValue:

initialDate: is for the Data Picker to show the Mentioned Date.

DateTimePickerFormField(
            dateOnly: true,
            format: dateFormat,
            decoration: InputDecoration(labelText: 'Select Date'),
            initialValue: DateTime.now(), //Add this in your Code.
            // initialDate: DateTime(2017),
            onSaved: (value) {
              debugPrint(value.toString());
            },
          ),

Updated Code with Validator:

  var _myKey = GlobalKey<FormState>();
  final dateFormat = DateFormat("dd-M-yyyy");
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Form(
          key: _myKey,
          child: Center(
            child: DateTimePickerFormField(
              dateOnly: true,
              format: dateFormat,
              validator: (val) {
                if (val != null) {
                  return null;
                } else {
                  return 'Date Field is Empty';
                }
              },
              decoration: InputDecoration(labelText: 'Select Date'),
              initialValue: DateTime.now(), //Add this in your Code.
              // initialDate: DateTime(2017),
              onSaved: (value) {
                debugPrint(value.toString());
              },
            ),
          ),
        ),
        RaisedButton(
          onPressed: () {
            if (_myKey.currentState.validate()) {
              _myKey.currentState.save();
            } else {
            }
          },
          child: Text('Submit'),
        )
      ],
    );
  }

Upvotes: 9

Related Questions