Skip to main content

Flutter: DatePicker Tutorial both with Material and Cupertino Style

Introduction

DatePicker is very important when you want the user to pick his / her date of birth or something else. In Flutter, implementing DatePicker is very easy and we will implement DatePicker in both Android or Material style and Cupertino or IOS style. 

Table of contents

  • Approach
  • Project Setup
  • Material Style DatePicker
  • Cupertino Style DatePicker
  • Conclusion

Approach

Flutter has widgets for everything and even for DatePicker. DatePicker widget is loaded with all needed animation and colours. So implementation is very easy. 

Project Setup

No extra plugins are required for this project and you can continue with your existing project.

Here is the starting code.
class DatePickerTutorial extends StatefulWidget {
  const DatePickerTutorial({Key? key}) : super(key: key);

  @override
  _DatePickerTutorialState createState() => _DatePickerTutorialState();
}

class _DatePickerTutorialState extends State<DatePickerTutorial> {
  String dob = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker Tutorial"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              "Your Date of Birth",
              style: TextStyle(
                fontSize: 32.0,
              ),
            ),
            Text(dob),
            OutlinedButton(
              onPressed: () {
                // TODO: Implement pick date
              },
              child: Text("Select Date"),
              style: OutlinedButton.styleFrom(
                primary: Colors.white,
                backgroundColor: Colors.indigo[600],
                textStyle: TextStyle(
                  fontSize: 32,
                  color: Colors.white,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Run the code and the result will be as follows.
Starting App

As you can see we have set up our UI. Only DatePicker is left so let's implement it in the next section.

Material Style

In Flutter, we have a function called showDatePicker() which when called shows the DatePicker dialog where the user selects a date.
showDatePicker() returns Future<DateTime?> type of data. So it is an asynchronous function. Also when the user presses the cancel button, it returns a null value.
Let's implement it in our app.

In the TODO line, remove the line and add the following code.
showDatePicker(
  context: context,
  initialDate: ,
  firstDate: ,
  lastDate: ,
);

It has four required fields.
  • context: The context is passed for the reference on where to show it. Simply pass the context.
  • initialDate: It is the initial date of selection you want. Pass any date and time you want in range in DateTime form
  • firstDate: It is the initial date of selection you want. If you want every applicant to be born after 2002 then pass DateTime(2002).
  • lastDate: It is the last date which the user can select. If you want the Date of Birth as in our case we will pass DateTime.now().
Now also I want to store the Date that is selected. So here is the code for that.
onPressed: () async {
  DateTime? date = await showDatePicker(
    context: context,
    initialDate: DateTime.now(),
    firstDate: DateTime(1950),
    lastDate: DateTime.now(),
  );
  if (date != null)
    setState(() {
      dob = "${date.day} / ${date.month} / ${date.year}";
    });
},


Here the initialDate and lastDate is DateTime.now() and the firstDate that the user can select is after 1950.

Now run the code.
Material Style DatePicker

Cupertino Style

The default date picker is of Material style.

Approach of CupertinoDatePicker is different. First we need to initialize CupertinoDatePicker with the initialDate, minimumDate and maximumDate and then we have a function called showCupertinoModelPopup function which shows a ModalBottomSheet. In the build method we will return the date picker.

Here is the code for that,
CupertinoDatePicker datePicker = CupertinoDatePicker(
  backgroundColor: Colors.white,
  minimumDate: DateTime(1950),
  initialDateTime: DateTime.now(),
  maximumDate: DateTime.now(),
  mode: CupertinoDatePickerMode.date,
  onDateTimeChanged: (date) {
    setState(() {
      dob = "${date.day} / ${date.month} / ${date.year}";
    });
  },
);
showCupertinoModalPopup(
  context: context,
  builder: (context) {
    return Container(
      height: 200,
      child: datePicker,
    );
  },
);

Here in the CupertinoDatePicker, we have a required field and that's onDateTimeChangedFunction which has a parameter of the selected date. So whenever the user changes the date, we will update it using the setState((){}) function.

Run the code and see the result.
Cupertino Style




Here is the full code for Material Style.
class DatePickerTutorial extends StatefulWidget {
  const DatePickerTutorial({Key? key}) : super(key: key);

  @override
  _DatePickerTutorialState createState() => _DatePickerTutorialState();
}

class _DatePickerTutorialState extends State<DatePickerTutorial> {
  String dob = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker Tutorial"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              "Your Date of Birth",
              style: TextStyle(
                fontSize: 32.0,
              ),
            ),
            Text(dob),
            OutlinedButton(
              onPressed: () async {
                DateTime? date = await showDatePicker(
                  context: context,
                  initialDate: DateTime.now(),
                  firstDate: DateTime(1950),
                  lastDate: DateTime.now(),
                );
                if (date != null)
                  setState(() {
                    dob = "${date.day} / ${date.month} / ${date.year}";
                  });
              },
              child: Text("Select Date"),
              style: OutlinedButton.styleFrom(
                primary: Colors.white,
                backgroundColor: Colors.indigo[600],
                textStyle: TextStyle(
                  fontSize: 32,
                  color: Colors.white,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}


Here is the full code for Cupertino style
class DatePickerTutorial extends StatefulWidget {
  const DatePickerTutorial({Key? key}) : super(key: key);

  @override
  _DatePickerTutorialState createState() => _DatePickerTutorialState();
}

class _DatePickerTutorialState extends State<DatePickerTutorial> {
  String dob = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker Tutorial"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              "Your Date of Birth",
              style: TextStyle(
                fontSize: 32.0,
              ),
            ),
            Text(dob),
            OutlinedButton(
              onPressed: () async {
                CupertinoDatePicker datePicker = CupertinoDatePicker(
                  backgroundColor: Colors.white,
                  minimumDate: DateTime(1950),
                  initialDateTime: DateTime.now(),
                  maximumDate: DateTime.now(),
                  mode: CupertinoDatePickerMode.date,
                  onDateTimeChanged: (date) {
                    setState(() {
                      dob = "${date.day} / ${date.month} / ${date.year}";
                    });
                  },
                );
                showCupertinoModalPopup(
                  context: context,
                  builder: (context) {
                    return Container(
                      height: 200,
                      child: datePicker,
                    );
                  },
                );
              },
              child: Text("Select Date"),
              style: OutlinedButton.styleFrom(
                primary: Colors.white,
                backgroundColor: Colors.indigo[600],
                textStyle: TextStyle(
                  fontSize: 32,
                  color: Colors.white,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Conclusion

We have learned how to implement DatePicker in both Material And Cupertino style. Hope you liked the tutorial and if you have any doubts comment below.












Comments

Popular posts from this blog

Animated Navigation in Flutter

  Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition.   Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition. Table of Contents Project Setup Code Result Project Setup Before directly applying to your existing project, practice the code in some example projects. For this tutorial, we are going to name our project screen_animation_tutorial. Open in VSCode or Android Studio. After that, we will make two Screens. The first Screen will be the Starting screen and the next Screen will be the Final Screen. So go ahead and create two dart files under the lib folder. The main.dart file code should look like this Dart import 'package:flutter/material.dart'; import 'package:screen_animation_tutorial/start_screen.dart'; void ...

How to create Snackbars in Flutter | Snackbar Tutorial

In this article, we will create and display different types of SnackBars in Flutter.  SnackBars in Flutter SnackBars are used to briefly display some information or inform the user about an action. For instance, when a user deletes a mail or message you may want to inform the user about the action. Also, the user can undo the action he performed by the undo button in the Snackbar . Syntax For creating a SnackBar, we use the following code. ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: content)); Inside the content field of SnackBar, we will pass the content. Any content can be passed inside it, but in practice, small messages with or without a button. Example Simple SnackBar class SnackBarTutorial extends StatelessWidget {   const SnackBarTutorial({Key? key}) : super (key: key);   @override   Widget build(BuildContext context) { ...

Flutter : Image Picker Tutorial | Pick single image from Gallery

Introduction In this tutorial, we will create an image picker and display the content on the screen . I mage Picker picks a file from the Storage or Camera and stores it in an XFile object. Implementation Install dependency We will first need the image_picker dependency . To install it, add the following dependency to pubspec.yaml file. image_picker: ^0.8.4+3 Then click on Get Packages in your IDE or run the following command on your Terminal / Command Prompt. flutter pub get Example Import the dependency in your dart file. import 'package:image_picker/image_picker.dart' ; Syntax Image picking is a future task . So we need to await the image picking . Here is the syntax. await _picker.pickImage( source : ImageSource.gallery); Here we have provided the source from the gallery . We can also provide the source as a Camera using the following syntax. await _picker.pickImage( source : Ima...