如何在Flutter中为日期选择器设置默认日期?

时间:2018-12-19 10:11:43

标签: dart flutter

以下代码正常运行。但是我不知道如何设置默认日期值!

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

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

我正在使用datetime_picker_formfield: flutter库。

我正在尝试使用initialDate: DateTime.now()初始日期属性来执行此操作,但是它没有显示任何内容作为初始值。

谢谢!

1 个答案:

答案 0 :(得分:2)

为了显示初始日期值,您需要使用-initialValue:

initialDate:用于让数据选择器显示提及的日期。

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

使用验证程序更新代码:

  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'),
        )
      ],
    );
  }
相关问题