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

Flutter: DraggableScrollableSheet widget Tutorial

Introduction In this tutorial, we are going to learn about the DraggableScrollableSheet widget. It is a widget that responds to user gestures. When the user drags from the bottom of the screen in the upward direction, the widget opens up and when scrolls down the widget close. The final app will look as follows  Final App DraggableScrollableSheet It is a widget that scrolls up and down of the viewport or screen according to the user's screen gestures. This widget becomes handy when you want to give some extra details which are lengthy content but don't want to navigate to a new screen. You might have come across many apps that implement the same thing. So let us learn to implement DraggableScrollableSheet in our own app. Approach The approach of our project is very simple. In our app, we are going to display some names of countries with the help of the  ListView.builder  and Li...

Flutter | Material Banner Tutorial

In this tutorial, we will create and display Material Banner in Flutter . Material Banners are displayed at the top of the screen . User interaction is required to dismiss the banner . Material Banner Material Banner alerts the user about action and p rovides some actions for the user to take . In brief, it alerts the user about an issue and the user address the issue . The user should dismiss the banner to remove it from the screen else it will be active. Syntax  ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: content, actions: actions)) Code Here is our starting class. It is a stateless class and we will display a banner when the Button is pressed. class SnackBarTutorial extends StatelessWidget { const SnackBarTutorial({Key ? key}) : super ( key: key); @ override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Material Banner"...