如何在颤振的日期选择器中仅显示年份?



我希望程序只要求用户输入年份。但如您所知,日期选择器会要求完整的日期,包括月份和日期。有没有办法让用户只被问到年份?

Afaik,你不能使用 datePicker 只选择年份。但是你可以通过使用对话框和YearPicker小部件来完成。

下面是一个示例代码,用于显示带有 YearPicker 的对话框(阅读注释(:

showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Select Year"),
content: Container( // Need to use container to add size constraint.
width: 300,
height: 300,
child: YearPicker(
firstDate: DateTime(DateTime.now().year - 100, 1),
lastDate: DateTime(DateTime.now().year + 100, 1),
initialDate: DateTime.now(),
// save the selected date to _selectedDate DateTime variable.
// It's used to set the previous selected date when
// re-showing the dialog.
selectedDate: _selectedDate,
onChanged: (DateTime dateTime) {
// close the dialog when year is selected.
Navigator.pop(context);
// Do something with the dateTime selected.
// Remember that you need to use dateTime.year to get the year
},
),
),
);
},
);

您可以使用此代码段选择年份,它是使用"警报"对话框的自定义年份选择器。

// Call this in the select year button.
void _pickYear(BuildContext context) {
showDialog(
context: context,
builder: (context) {
final Size size = MediaQuery.of(context).size;
return AlertDialog(
title: Text('Select a Year'),
// Changing default contentPadding to make the content looks better
contentPadding: const EdgeInsets.all(10),
content: SizedBox(
// Giving some size to the dialog so the gridview know its bounds
height: size.height / 3,
width: size.width,
//  Creating a grid view with 3 elements per line.
child: GridView.count(
crossAxisCount: 3,
children: [
// Generating a list of 123 years starting from 2022
// Change it depending on your needs.
...List.generate(
123,
(index) => InkWell(
onTap: () {
// The action you want to happen when you select the year below,
// Quitting the dialog through navigator.
Navigator.pop(context);
},
// This part is up to you, it's only ui elements
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Chip(
label: Container(
padding: const EdgeInsets.all(5),
child: Text(
// Showing the year text, it starts from 2022 and ends in 1900 (you can modify this as you like)
(2022 - index).toString(),
),
),
),
),
),
),
],
),
),
);
},
);
}

相关内容

  • 没有找到相关文章

最新更新