How to Display a Date Picker in Flutter

Flutter Jul 2, 2023

Flutter provides convenient widgets and functions to make it easy to display and select dates. In this post, we will build our own date picker using the showDatePicker function. We will also go over some optional properties to customize our date picker.

flutter_date_picker

Creating the Date Picker Widget

To begin, we will create a separate widget for our date picker functionality. This approach ensures reusability and keeps our code organized. For this, we create a new file called date_picker.dart in the lib directory of our Flutter project. Open the file and add the following code:

import 'package:flutter/material.dart';

class DatePicker extends StatefulWidget {
  @override
  _DatePickerState createState() => _DatePickerState();
}

class _DatePickerState extends State {
  DateTime? selectedDate;

  Future _selectDate(BuildContext context) async {
    final DateTime? selected = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2050),
    );

    if (selected != null && selected != selectedDate) {
      setState(() {
        selectedDate = selected;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          ElevatedButton(
            onPressed: () => _selectDate(context),
            child: Text('Select Date'),
          ),
          SizedBox(height: 16.0),
          Text(
            'Selected Date: ${selectedDate != null ? selectedDate.toString() : 'No date selected'}',
            style: TextStyle(fontSize: 18.0),
          ),
        ],
      ),
    );
  }
}

In this code, we have defined a DatePicker widget that extends a StatefulWidget. It contains a selectedDate variable to hold the currently selected date. The _selectDate function calls the showDatePicker function which is responsible for showing the date picker dialog. Inside the showDatePicker function we set the initialDate, firstDate and lastDate properties. Furthermore, the _selectDate function is also updating the selected date when a new date is selected.

The widget itself renders a Column widget with an ElevatedButton that triggers the _selectDate function when pressed. Below the button, we display the selected date or a message indicating that no date has been selected yet.

Using the DatePicker widget

Now that we have our DatePicker widget, we can import it into any file to use it. For this demo, we will be importing the widget inside our main.dart file:

import 'package:a_new_name/date_picker.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Date Picker Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Date Picker Demo'),
        ),
        body: DatePicker(),
      ),
    );
  }
}

In the above code, we import the DatePicker widget from the date_picker.dart file. In the MyApp widget, we have a Scaffold widget with an AppBar widget. Inside the Scaffold widget, we place the DatePicker widget as the body. And now we are ready to test our date picker:

flutter_displaying_and_using_the_date_time_picker

The GIF shows the date selection feature, allowing users to choose a date by either selecting from the calendar or manually entering the date using the keyboard.

Customizing the date picker

You can customize the date picker to fit your application's design and enhance the user experience. The showDatePicker function offers optional properties to change the displayed texts. See the properties below:

  • helpText: Sets the help text shown above the date picker.
  • cancelText: Changes the text displayed on the cancel button.
  • confirmText: Modifies the text shown on the confirm button.
  • fieldHintText: Sets the hint text inside the date picker field.
  • fieldLabelText: Provides a label text for the date picker field.
  • errorInvalidText: Specifies the text for the error message when an invalid date is entered.

Additionally, we can customize the date picker's appearance using the builder property. By using the ThemeData class inside the Theme widget, we can change things like colors and borders. In the provided code example, we changed the color and the border of the date picker while also making the mentioned text customizations:

final DateTime? selected = await showDatePicker(
  context: context,
  initialDate: DateTime.now(),
  firstDate: DateTime(2000),
  lastDate: DateTime(2050),
  helpText: 'Select your birthdate',
  cancelText: 'Close',
  confirmText: 'Select',
  fieldHintText: 'Month/Date/Year',
  fieldLabelText: 'BirthDate',
  errorInvalidText: 'Please enter a valid date',
  builder: (BuildContext context, Widget? widget) => Theme(
    data: ThemeData(
      colorScheme: ColorScheme.light(
        primary: Colors.red,
      ),
      dialogTheme: DialogTheme(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(25),
        ),
      ),
    ),
    child: widget!,
  ),
);

This will result in the following changes:

flutter_changed_color_border_and_text_of_date_picker

In the above GIF, you can see that our changes to the text fields are applied and the colors have been changed.

Improving the date format for selected dates

In our demo, the selected dates are currently displayed in a format like this: 2023-07-02 00:00:00.000. However, we can make it more user-friendly by changing the format to something that looks better and is easier to understand.

To do this, we can use Flutter's built-in features for formatting dates. By applying these formatting options, we can change how the dates are displayed to better suit the preferences of our users.

For a step-by-step guide on how to format dates in Flutter, you can check out my previous post. In that post, I explain different techniques, such as using the intl package, customizing the date format, and handling dates in different languages. By following the instructions in that post, you will be able to easily improve the way the selected dates are shown in your Flutter application:

How to Format DateTime in Flutter
As a Flutter developer, you will often encounter the need to format dates in various formats and languages. In this post, we will explore different methods of formatting dates in Flutter, including the use of the DateTime class and the powerful intl package. We will also discuss best practices

Conclusion

In this post, we learned how to display a date picker in Flutter. We did this by creating a separate widget for the date picker functionality and using the showDatePicker function. We also went over some customization options for the showDatePicker function to make sure that the date picker fits within your application.

Tags