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

Flutter中如何动态设置DatePicker的lastDate为当前时间加20年

解决方案

你只需要将固定写死的DateTime(2100)替换为基于当前时间动态计算的20年后的日期即可,推荐直接操作年份数值实现,避免用Duration计算年数带来的闰年误差。

另外注意你代码里的小笔误:函数参数名contex少了字母t,应为context,否则调用上下文时会报错。同时建议将当前时间提前存入变量,避免多次调用DateTime.now()时刚好跨天导致的初始日期校验异常。

修改后的完整代码如下:

DateTime _date = DateTime.now();

Future<Null> _checkInDate(BuildContext context) async {
  // 提前获取当前时间,避免多次调用DateTime.now()出现时间不一致
  final now = DateTime.now();
  DateTime? _datePicker = await showDatePicker(
    context: context,
    builder: (BuildContext context, Widget? child) {
      return Theme(
        data: ThemeData(
          primaryColor: Color(0xFFEF5350),
          colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.red)
          .copyWith(secondary: Color(0xFFFFF176)),
        ),
        child: child ?? const Text(""),
      );
    },
    initialDate: _date.isBefore(now) ? now : _date, // 加校验避免保存的_date早于当前时间报错
    firstDate: now,
    // 动态计算20年后的同一天作为lastDate
    lastDate: DateTime(now.year + 20, now.month, now.day),
  );
  if (_datePicker != null && _datePicker != _date) {
    _checkInController.text = DateFormat('dd-MM-yyyy').format(_datePicker);
  }
}

如果你的业务允许选择的最大日期精确到年、不需要保留同月同日,直接写lastDate: DateTime(now.year + 20)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:54:02