You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Dart中设置生日日期不能晚于当前日期?

解决FormBuilderDateTimePicker无法限制选择未来生日日期的问题

你设置的initialDate: DateTime.now()只是指定日期选择器打开时默认选中的日期,并不是限制用户能选择的最晚日期,这就是该设置未生效的原因。

要禁止选择今日之后的日期,你需要添加lastDate参数并设置为DateTime.now()(也可以设置为精确的当天日期,避免时间部分干扰):

修改后的代码如下:

Container( 
  width: CustomSizes(context).getWidth(context) * .45, 
  child: FormBuilderDateTimePicker(
    name: 'birthday',
    // onChanged: _onChanged,
    inputType: InputType.date,
    initialDate: DateTime.now(), // 保留初始选中日期的设置
    lastDate: DateTime.now(), // 新增:限制可选的最晚日期为今日
    // 如果需要更精确的当天时间范围,可替换为:
    // lastDate: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day),
    format: DateFormat('M-dd-y'),
    decoration: InputDecoration(
      labelText: 'Birthday',
    ),
  ),
)

补充说明

  • initialDate:控制日期选择器打开时默认高亮的日期,不限制用户选择范围
  • lastDate:设置用户能选择的最晚日期,超过该日期的选项会被禁用
  • 若担心DateTime.now()的时间部分影响当天日期的选择(比如当前时间为下午,是否会导致当天无法选中),可以用DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day)确保限制范围为当天结束前的所有日期

内容的提问来源于stack exchange,提问作者Betty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 10:05:14