How to only display the year in datepicker for Flutter?
4,584
Afaik, you can't use datePicker to only select the year. But you can do it by using dialog and a YearPicker widget.
Here a sample code to show dialog with a YearPicker (read the comment):
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
},
),
),
);
},
);
Author by
gribble
Updated on December 18, 2022Comments
-
gribble over 1 year
I want to the program to only ask the user for year input. But as you know, the date picker asks for a full date, including month and day. Is there a way to make it so that the user is only asked of the year?