I've created a form using Flutter which has date picker.
User is supposed to pick his/her date of birth using it to make sure if the user is 16 and above. How do I validate date of birth to age 16?
Here are the parts of the code:
class _WelcomeScreenState extends State<WelcomeScreen> {
TextEditingController dateinput = TextEditingController();
final formKey = GlobalKey<FormState>();
String name = "";
@override
void initState() {
dateinput.text = ""; //set the initial value of text field
super.initState();
}
--
GestureDetector(
child: TextField(
style: TextStyle(color: Colors.white),
controller:
dateinput, //editing controller of this TextField
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.white),
icon: Icon(Icons.calendar_today),
iconColor: Colors.white, //icon of text field
labelText: "Enter Date Of Birth" //label text of field
),
readOnly:
true, //set it true, so that user will not able to edit text
onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(
1900), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2040));
if (pickedDate != null) {
print(
pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
String formattedDate =
DateFormat('dd-MM-yyyy').format(pickedDate);
print(
formattedDate); //formatted date output using intl package => 2021-03-16
//you can implement different kind of Date Format here according to your requirement
setState(() {
dateinput.text =
formattedDate; //set output date to TextField value.
});
} else {
print("Date is not selected");
}
},
),
),