Date Picker

  1. The showDatePicker function
  2. Shows a dialog containing a Material Design date picker.

    Basic Code :

        showDatePicker(

          contextcontext,

          initialDateDateTime.now(),

          firstDateDateTime(2000),

          lastDateDateTime(2025),

        );




    The showDatePicker function

  3. Example :

    1. Prepare a variable :
    2. DateTime selectedDate = DateTime.now();



    3. Setup UI
    4.       Column(

              mainAxisSizeMainAxisSize.min,

              children: <Widget>[

                Text(

                  "${selectedDate.toLocal()}".split(' ')[0],

                  styleTextStyle(fontSize55fontWeightFontWeight.bold),

                ),

                SizedBox(

                  height20.0,

                ),

                RaisedButton(

                  onPressed: () => _selectDate(context), // Refer step 3

                  childText(

                    'Select date',

                    style:

                        TextStyle(colorColors.blackfontWeightFontWeight.bold),

                  ),

                  colorColors.greenAccent,

                ),

              ],

            ),



      A minimal UI consists of Text to show date and RaisedButton to open DatePicker dialog.

    5. Write a Method to call showDatePicker function
    6.     _selectDate(BuildContext contextasync {

            final DateTimepicked = await showDatePicker(

              contextcontext,

              initialDateselectedDate// Refer step 1

              firstDateDateTime(2000),

              lastDateDateTime(2025),

            );

            if (picked != null && picked != selectedDate)

              setState(() {

                selectedDate = picked;

              });

          }


      This method actually calls showDatePicker function and waits for the date selected by the user. If a user does not select anything then the date return will be null otherwise the selected date.

      Note :

      The initialDate property is used to display a default date when DatePicker dialog is opened.

      SetState will be called to update the selected date in UI and you are done.




  4. Display only a specific date range
  5. We need to set the firstDate and the lastDate properties :


        showDatePicker(

          contextcontext,

          initialDateselectedDate,

          firstDateDateTime(2000), // Required

          lastDateDateTime(2025), // Required

        );



  6. Show the Text input box instead of the calendar
  7. Sometimes it becomes difficult for old age people to interact with the calendar for changing the dates especially when they use it for the first time.

    In such a situation it is better to just provide an input box to enter the date, and this can be done very easily just by setting initialEntryMode property.


        showDatePicker(

          contextcontext,

          initialDateselectedDate,

          firstDateDateTime(2000),

          lastDateDateTime(2025),

          initialEntryModeDatePickerEntryMode.input,

        );




  8. Show the year’s list first
  9. Sometimes you are very sure that the user will enter the date from the past years like date of birth, In such a case you can directly show the year’s list instead of showing a list of days then making users open the year list.

    Setting initialDatePickerMode to DatePickerMode.year will do the work. This will save one-click for users, which is good.

        showDatePicker(

          contextcontext,

          initialDateselectedDate,

          firstDateDateTime(2000),

          lastDateDateTime(2025),

          initialDatePickerModeDatePickerMode.year,

        );





  10. Change the Text and the error messages.
  11. These highlighted texts can be changed very easily by setting below properties.

    When the user tries to enter the date via text input box, there is a high chance of making a mistake like giving an invalid date.

    By default, this widget provides some predefined error text but you can always change it if you want in a case like assisting users what to do next instead of just showing the message.


        showDatePicker(

            contextcontext,

            initialDateselectedDate,

            firstDateDateTime(2000),

            lastDateDateTime(2025),

            helpText'Select booking date'// Can be used as title

            cancelText'Not now',

            confirmText'Book',

            errorFormatText'Enter valid date',

            errorInvalidText'Enter date in valid range'

        );




  12. Change the label and hint text

  13.     showDatePicker(

          contextcontext,

          initialDateselectedDate,

          firstDateDateTime(2000),

          lastDateDateTime(2025),

          fieldLabelText'Booking date',

          fieldHintText'Month/Date/Year',

        );






  14. Open native-like DatePicker in the Target platform
  15. If you have noticed carefully that we have kept on opening Material design date picker in the iOS device! so how do we go for Cupertino Datepicker in iOS?

    We just need to check which target platform it is and show the respective DatePicker and yes Flutter has also covered the CupertinoDatePicker.

    import 'package:flutter/cupertino.dart';

    import 'package:flutter/material.dart';

     

    import 'package:flutter/foundation.dart';

     

    void main() {

      runApp(const MyApp());

    }

     

    class MyApp extends StatelessWidget {

      const MyApp({Keykey}) : super(keykey);

     

      @override

      Widget build(BuildContext context) {

        return MaterialApp(

          title'DatePicker',

          themeThemeData(

            primarySwatchColors.blue,

          ),

          homeconst MyHomePage(),

        );

      }

    }

     

    class MyHomePage extends StatefulWidget {

      const MyHomePage({Keykey}) : super(keykey);

     

      @override

      State<MyHomePagecreateState() => _MyHomePageState();

    }

     

    class _MyHomePageState extends State<MyHomePage> {

      DateTime selectedDate = DateTime.now();

     

      @override

      Widget build(BuildContext context) {

        buildMaterialDatePicker(BuildContext contextasync {

          final DateTimepicked = await showDatePicker(

            contextcontext,

            initialDateselectedDate,

            firstDateDateTime(2000),

            lastDateDateTime(2025),

            builder: (contextchild) {

              return Theme(

                dataThemeData.light(),

                childchild!,

              );

            },

          );

          if (picked != null && picked != selectedDate) {

            setState(() {

              selectedDate = picked;

            });

          }

        }

     

        buildCupertinoDatePicker(BuildContext context) {

          showModalBottomSheet(

              contextcontext,

              builder: (BuildContext builder) {

                return Container(

                  heightMediaQuery.of(context).copyWith().size.height / 3,

                  colorColors.white,

                  childCupertinoDatePicker(

                    modeCupertinoDatePickerMode.date,

                    onDateTimeChanged: (picked) {

                      if (picked != selectedDate) {

                        setState(() {

                          selectedDate = picked;

                        });

                      }

                    },

                    initialDateTimeselectedDate,

                    minimumYear2000,

                    maximumYear2025,

                  ),

                );

              });

        }

     

        _selectDate(BuildContext contextasync {

          switch (Theme.of(context).platform) {

            case TargetPlatform.android:

            case TargetPlatform.fuchsia:

            case TargetPlatform.linux:

            case TargetPlatform.windows:

              return buildMaterialDatePicker(context);

            case TargetPlatform.iOS:

            case TargetPlatform.macOS:

              return buildCupertinoDatePicker(context);

          }

        }

     

        return Scaffold(

          backgroundColorColors.teal,

          bodyCenter(

            childColumn(

              mainAxisSizeMainAxisSize.min,

              children: <Widget>[

                Text(

                  "${selectedDate.toLocal()}".split(' ')[0],

                  styleconst TextStyle(fontSize55fontWeightFontWeight.bold),

                ),

                const SizedBox(

                  height20.0,

                ),

                TextButton(

                  onPressed: () => _selectDate(context), // Refer step 3

                  childconst Text(

                    'Select date',

                    style:

                        TextStyle(colorColors.blackfontWeightFontWeight.bold),

                  ),

                ),

              ],

            ),

          ),

        );

      }

    }









Sources :

A Deep Dive Into DatePicker In Flutter
showDatePicker function