Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only display the year in datepicker for Flutter?

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?

like image 685
gribble Avatar asked May 26 '20 12:05

gribble


1 Answers

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
              },
            ),
          ),
        );
      },
    );
like image 50
ישו אוהב אותך Avatar answered Oct 21 '22 22:10

ישו אוהב אותך