Date and Time Picker In Flutter

Date and Time Picker in Flutter

In this article, we will discuss the Date and Time Picker in a flutter. What we shall do today is to add 3 buttons vertical on the screen. The first button is used to show the date picker and the Second button is used to show the timer picker and the third button is used to show the combined date and time. We also show its date and time on the Text Widget. We, Will, used an intl package in order to format the date and time in our application. For this, we will add packages to pubspec.yaml (and run a flutter pub get to install this package):

dependencies:
  intl: ^0.17.0

Date and Time Picker

A date and time picker for a flutter, mean we can choose date time in English, Dutch, and any other language you will want, and we can also customize our own picker content. DatePicker and Timer Picker is a material widget in a flutter that lets the user select a date and time. Since there is no widget available for creating a date picker and time picker we will use showDatePicker() function and showTimePicker() Function. It will display a Material Design date picker and time picker in a dialog by calling flutter’s inbuilt function.

To create a DatePicker and Time Picker in Flutter we will use showDatePicker()  and showTimePicker() which is an asynchronous function. When we call the function it will display the dialog where the user can select date as well as Time. It returns the selected date and time when the user confirms the dialog. If the user cancels the dialog, it will return null. We can display the date anywhere or save it in shared preferences for future use.

Constructor for Date Picker

The Date picker required properties initialDatefirstDate, and lastDate without which we cannot use the Date Picker.

initialDate It is the date that we want to display when the date picker is displayed for the first time. It should lie between firstDate and lastDate.
for the initial date, we can show the current date as well. The currentDate represents today’s date & it will be highlighted in the day grid. If we don’t provide any value, it will use the date of DateTime.now().
firstDateIt is the earliest date that we want the user to choose from
lastDateIt is the max possible date that the user can select.

Constructor for Time picker

The Time picker required properties initialTime without which we cannot use the Date Picker. The initialTime has a type of TimeOfDay which describes the time in the beginning when the user opens the dialog box. for the initialTime, we can show the current time as well. The current time represents today’s Time & it will be highlighted in the Time Grid. If we don’t provide any value, it will use the date of TimeOfDay.now().

Creating a Date and Time Picker in Flutter

Let’s take a basic example of how to use a date and time picker in our application.

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

@override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: TextScreen(),
    );
  }
}

class TextScreen extends StatefulWidget {
  const TextScreen({
    Key? key,
  }) : super(key: key);

  @override
  State<TextScreen> createState() => _TextScreenState();
}

class _TextScreenState extends State<TextScreen> {
  DateTime selectedDate = DateTime.now();
  TimeOfDay selectedTime = TimeOfDay.now();
  DateTime dateTime = DateTime.now();
  bool showDate = false;
  bool showTime = false;
  bool showDateTime = false;

   // Select for Date
  Future<DateTime> _selectDate(BuildContext context) async {
    final selected = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime(2025),
    );
    if (selected != null && selected != selectedDate) {
      setState(() {
        selectedDate = selected;
      });
    }
    return selectedDate;
  }

// Select for Time
  Future<TimeOfDay> _selectTime(BuildContext context) async {
    final selected = await showTimePicker(
      context: context,
      initialTime: selectedTime,
    );
    if (selected != null && selected != selectedTime) {
      setState(() {
        selectedTime = selected;
      });
    }
    return selectedTime;
  }
  // select date time picker

  Future _selectDateTime(BuildContext context) async {
    final date = await _selectDate(context);
      if (date == null) return;

    final time = await _selectTime(context);

      if (time == null) return;
    setState(() {
      dateTime = DateTime(
        date.year,
        date.month,
        date.day,
        time.hour,
        time.minute,
      );
    });
  }

 String getDate() {
    // ignore: unnecessary_null_comparison
    if (selectedDate == null) {
      return 'select date';
    } else {
      return DateFormat('MMM d, yyyy').format(selectedDate);
    }
  }

String getDateTime() {
    // ignore: unnecessary_null_comparison
    if (dateTime == null) {
      return 'select date timer';
    } else {
      return DateFormat('yyyy-MM-dd HH: ss a').format(dateTime);
    }
  }

 String getTime(TimeOfDay tod) {
    final now = DateTime.now();

    final dt = DateTime(now.year, now.month, now.day, tod.hour, tod.minute);
    final format = DateFormat.jm();
    return format.format(dt);
  }
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Date Timer Picker'),
        centerTitle: true,
        backgroundColor: Colors.teal,
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  _selectDate(context);
                  showDate = true;
                },
                child: const Text('Date Picker'),
              ),
            ),
            showDate ? Center(child: Text(getDate())) : const SizedBox(),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  _selectTime(context);
                  showTime = true;
                },
                child: const Text('Timer Picker'),
              ),
            ),
            showTime
                ? Center(child: Text(getTime(selectedTime)))
                : const SizedBox(),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  _selectDateTime(context);
                  showDateTime = true;
                },
                child: const Text('Select Date and Time Picker'),
              ),
            ),
            showDateTime
                ? Center(child: Text(getDateTime()))
                : const SizedBox(),
          ],
        ),
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below.

Select Date and Time Picker

Thank you for reading the guide on Date and Time Picker in Flutter.

Also Read: Stepper in Flutter.