【问题标题】:How to set the default date for the Date picker in flutter?如何在颤动中设置日期选择器的默认日期?
【发布时间】:2019-05-19 19:27:07
【问题描述】:

下面的代码工作正常。但是我不知道如何设置默认日期值!

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: 颤振库。

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

提前致谢!

【问题讨论】:

  • 你的意思是它没有显示在DatePicker 本身吗?还是开之前DatePicker
  • 它显示DatePicker,最初它的值为空。我想设置默认值。以后如果用户愿意,他可以根据自己的需要更改日期!
  • 并且默认值应该是今天的日期!
  • 不设置initialDate会怎样?
  • 它工作正常我没有设置initialDate

标签: dart flutter


【解决方案1】:

为了显示您需要使用的初始日期值 - 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'),
        )
      ],
    );
  }

【讨论】:

  • 还有一个查询。如何检查日期是否已设置?用于验证目的
  • 非常感谢你让我开心
  • TimeOfDay 时如何设置 initialValue?
【解决方案2】:

将 onSaved: 更改为 onChanged: 并添加 setState

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2021-03-14
    相关资源
    最近更新 更多