Working with Cupertino Date Picker in Flutter

Last updated on December 13, 2020 The Frog Loading... Post a comment

There are many times you need to implement a date picker that lets the user to select a date and time. If you are making an app in iOS style with Flutter, you may want to use CupertinoDatePicker. In general, CupertinoDatePicker goes along with showCupertinoModalPopup() or showCupertinoDialog().

In this article, we will have a look at CupertinoDatePicker and go over a complete example of implementing it.

Constructor and Parameters

Constructor

CupertinoDatePicker({
  Key key, 
  CupertinoDatePickerMode mode: CupertinoDatePickerMode.dateAndTime, 
  @required ValueChanged<DateTime> onDateTimeChanged, 
  DateTime initialDateTime, 
  DateTime minimumDate, 
  DateTime maximumDate, 
  int minimumYear: 1, 
  int maximumYear, 
  int minuteInterval: 1, 
  bool use24hFormat: false, 
  Color backgroundColor
})

Parameters

ParameterType/ClassDescription
backgroundColorColorBackground color of date picker
maximumDateDateTimeThe maximum selectable date that the picker can settle on
maximumYearintMaximum year that the picker can be scrolled to
minimumDateDateTimeThe minimum selectable date that the picker can settle on
minimumYearintMinimum year that the picker can be scrolled to
initialDateTimeDateTimeDefaults to the present date and time and must not be null. The present must conform to the intervals set in minimumDate, maximumDate, minimumYear, and maximumYear.
minuteIntervalintThe granularity of the minutes spinner, if it is shown in the current mode. Must be an integer factor of 60.
modeCupertinoDatePickerMode
onDateTimeChanged
(Required)
ValueChangedCallback called when the selected date and/or time changes
use24hFormatboolWhether to use 24 hour format. Defaults to false.

Example

In this example, we’ll create a tiny Flutter app that has a button. When the user clicks this button, a modal popup will show up. This modal popup contains a CupertinoDatePicker and a button which used to close the modal. Our app also has a Text widget that displays the date and time picked from the CupertinoDatePicker.

Beside CupertinoDatePicker, we’ll use the showCupertinoModalPopup() function to display the date picker at the bottom of the screen.

Preview:

The Code:

import 'package:flutter/cupertino.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      // hide the debug banner
      debugShowCheckedModeBanner: false,
      title: "Kindacode.com",
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  DateTime _chosenDateTime;

  // Show the modal that contains the CupertinoDatePicker
  void _showDatePicker(ctx) {
    // showCupertinoModalPopup is a built-in function of the cupertino library
    showCupertinoModalPopup(
        context: ctx,
        builder: (_) => Container(
          height: 500,
          color: Color.fromARGB(255, 255, 255, 255),
          child: Column(
            children: [
              Container(
                height: 400,
                child: CupertinoDatePicker(
                    initialDateTime: DateTime.now(),
                    onDateTimeChanged: (val) {
                      setState(() {
                        _chosenDateTime = val;
                      });
                    }),
              ),

              // Close the modal
              CupertinoButton(
                child: Text('OK'),
                onPressed: () => Navigator.of(ctx).pop(),
              )
            ],
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: Text('Kindacode.com'),
        // This button triggers the _showDatePicker function
        trailing: Container(child: CupertinoButton(
          padding: EdgeInsetsDirectional.zero,
          child: Text('Show Picker'),
          onPressed: () => _showDatePicker(context),
        ),),
      ),
      child: SafeArea(
        child: Center(
          child: Text(_chosenDateTime != null
              ? _chosenDateTime.toString()
              : 'No date time picked!'),
        ),
      ),
    );
  }
}

The point of this article is to help you get acquainted with CupertinoDatePicker so we don’t spend much time on the UI. You can improve it on your own.

Conclusion

This article went over the basics of working with CupertinoDatePicker in Flutter. Continue learning more by taking a look at our Flutter category page or the following articles:

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x