如何增加DateTime.现在在达特



我试图使用在扑动的DatePicker,我想设置initialDate为DateTime.now()和lastDate我想设置为DateTime.now() + 20年,所以它增加了一年动态。目前,我将lastDate设置为年份(2100),但是当年份达到2101时,这会导致问题。那么,如何修改函数来动态地增加lastDate呢?

下面是我的函数:

DateTime _date = DateTime.now();
Future < Null > _checkInDate(BuildContext contex) async {
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 ? ? Text(""),
);
},
initialDate: _date,
firstDate: DateTime.now(),
lastDate: DateTime(2100), //how can i increase the lastDate dynamically?
);
if (_datePicker != null && _datePicker != _date) {
_checkInController.text = DateFormat('dd-MM-yyyy').format(_datePicker);
}
}

可以,使用DateTime.now().year获得当前年份,然后添加您想要的年份。这样的:

final date = DateTime(DateTime.now().year + 20);