如何将日期限制设置为从当前日期 Flutter 起 6 个月?

How to set Date limit to 6 months from current date Flutter?

我需要将日历限制设置为从现在起的接下来 6 个月。我尝试 运行 的代码如下:

Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime.now(),
        lastDate: DateTime(DateTime.now().month + 6));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

当我尝试 运行 这段代码时,我得到了给定的错误:

Unhandled Exception: 'package:flutter/src/material/date_picker.dart': Failed assertion: line 226 pos 5: '!lastDate.isBefore(firstDate)': lastDate 0008-01-01 00:00:00.000 must be on or after firstDate 2022-02-09 00:00:00.000.
E/flutter ( 1931): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1931): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)

您的 lastDate 输入 DateTime(DateTime.now().month + 6)) 不正确。

由于 DateTime.now().month + 6 将产生 intDateTime(DateTime.now().month + 6)) 将是年份 DateTime.now().month + 6

将该行更改为:

lastDate: DateTime(DateTime.now().year, DateTime.now().month + 6, DateTime.now().day));

或使用 .add 函数 DateTime class:

DateTime.now().add(const Duration(days: 180));

向 DateTime 添加内容的一种简洁方法是:

DateTime myDate = DateTime.now();
DateTime myDateWithSixMonthsAdded = myDate.add(Duration(days: 180));

添加 180 天,因为 Duration 没有 months 参数。