DateTime Picker in Flutter

Create Free Backend With Appwrite

Introduction

The DateTime Picker is a widget that allows users to select a date, time, or both from a dialog. This is very useful for apps that require you to input dates or times, like scheduling events or setting reminders.

Example 1: BirthDate Picker

In this example, you will learn to create a date picker for selecting a birthdate.

DateTime? selectedDate;

Future<void> _selectDate(BuildContext context) async {
  final DateTime? picked = await showDatePicker(
    context: context,
    initialDate: DateTime.now(),
    firstDate: DateTime(1900),
    lastDate: DateTime.now(),
  );
  if (picked != null && picked != selectedDate)
    setState(() {
      selectedDate = picked;
    });
}
Run Online

Example 2: Attendance Time Picker

In this example, you will learn to create a time picker for selecting attendance time.

TimeOfDay? selectedTime;

Future<void> _selectTime(BuildContext context) async {
  final TimeOfDay? picked = await showTimePicker(
    context: context,
    initialTime: TimeOfDay.now(),
  );
  if (picked != null && picked != selectedTime)
    setState(() {
      selectedTime = picked;
    });
}
Run Online

Example 3: Combined DateTime Picker

In this example, you will learn to create a combined date and time picker.

DateTime? selectedDateTime;

Future<void> _selectDateTime(BuildContext context) async {
  final DateTime? picked = await showDatePicker(
    context: context,
    initialDate: DateTime.now(),
    firstDate: DateTime(1900),
    lastDate: DateTime.now(),
  );
  if (picked != null) {
    final TimeOfDay? pickedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (pickedTime != null) {
      setState(() {
        selectedDateTime = DateTime(
          picked.year,
          picked.month,
          picked.day,
          pickedTime.hour,
          pickedTime.minute,
        );
      });
    }
  }
}
Run Online

Challenge

Create application that find age from the selected birthdate and display it in the app.