Working with Cupertino Date Picker in Flutter

Last updated on May 17, 2021 The Frog Loading... Post a comment

There are many times you need to implement a date picker that lets the user 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 go over a complete example of implementing CupertinoDatePicker and have a look at its available options.

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 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.

App Preview

The Code

Don’t forget to import the Cupertino library:

import 'package:flutter/cupertino.dart';

Here’s the full source code:

// main.dart
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!'),
        ),
      ),
    );
  }
}

This article aims to help you get acquainted with CupertinoDatePicker so we don’t spend much time on the UI. You can improve it on your own.

API

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
})

Options

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.

Conclusion

This article went over the fundamentals of using with CupertinoDatePicker to make an iOS-style appearance for your apps. If you’d like to learn more new and interesting stuff about Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page, or Dart topic page for the latest tutorials and examples.

Related Articles

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