在 showDatePicker 中使用当前年份作为 firstDate
Use current year as firstDate in showDatePicker
我开始学习 flutter 并且正在使用 showDatePicker
在那里,我可以手动将当前年份分配给 firstDate
firstDate: DateTime(2021)
我正在尝试自动将当前年份用作 firstDate
。
为此,我到目前为止所做的是:
void _showDatePicker() {
var currentYear = DateFormat.y().format(DateTime.now()) as DateTime;
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: currentYear,
lastDate: DateTime.now()
);
}
如果我删除 as DateTime
我会在 firstDate: currentYear
中得到错误:
The argument type 'String' can't be assigned to the parameter type 'DateTime'
如果我添加 as DateTime
,我会得到错误:
type 'String' is not a subtype of type 'DateTime' in type cast
我该如何解决?
嘿,请尝试下面的代码。
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2025),
)
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime.now()
);
我已对您的代码进行了一些更改,此代码适合您。
您当前的年份是字符串,所以我已将其转换为 int,然后传入 DateTime()
void _showDatePicker() {
int currentYear = int.parse(DateFormat.y().format(DateTime.now()));
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(currentYear),
lastDate: DateTime.now());
}
更简单、更高效的解决方案是根本不使用字符串。它们是不必要的,会增加额外的开销。
您可以从 DateTime
对象中获取当前年份。并将其传递给默认的 DateTime
构造函数。没有字符串转换,没有 intl
包,从字符串中解析日期没有性能损失。
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year),
lastDate: DateTime.now()
);
我开始学习 flutter 并且正在使用 showDatePicker
在那里,我可以手动将当前年份分配给 firstDate
firstDate: DateTime(2021)
我正在尝试自动将当前年份用作 firstDate
。
为此,我到目前为止所做的是:
void _showDatePicker() {
var currentYear = DateFormat.y().format(DateTime.now()) as DateTime;
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: currentYear,
lastDate: DateTime.now()
);
}
如果我删除 as DateTime
我会在 firstDate: currentYear
中得到错误:
The argument type 'String' can't be assigned to the parameter type 'DateTime'
如果我添加 as DateTime
,我会得到错误:
type 'String' is not a subtype of type 'DateTime' in type cast
我该如何解决?
嘿,请尝试下面的代码。
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2025),
)
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime.now()
);
我已对您的代码进行了一些更改,此代码适合您。
您当前的年份是字符串,所以我已将其转换为 int,然后传入 DateTime()
void _showDatePicker() {
int currentYear = int.parse(DateFormat.y().format(DateTime.now()));
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(currentYear),
lastDate: DateTime.now());
}
更简单、更高效的解决方案是根本不使用字符串。它们是不必要的,会增加额外的开销。
您可以从 DateTime
对象中获取当前年份。并将其传递给默认的 DateTime
构造函数。没有字符串转换,没有 intl
包,从字符串中解析日期没有性能损失。
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year),
lastDate: DateTime.now()
);