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?
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?
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
},
),
),
);
},
);
You can use this snippet to select a year, it's a custom year picker using Alert dialog.
// 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(),
),
),
),
),
),
),
],
),
),
);
},
);
}