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

gri*_*ble 9 mobile android ios dart flutter

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

ישו*_*ותך 26

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
              },
            ),
          ),
        );
      },
    );
Run Code Online (Sandbox Code Playgroud)