How to Add Date Picker in Flutter

Date picker is an important component when you have text fields such as sign up form in your mobile application. It can be used for picking dates, such as date of birth. In this blog post, I am explaining how to add a date picker in flutter.

If you don’t know how to add TextField in flutter then please go through this blog post before proceeding. In this flutter date picker example, I am using a TextField widget. When the TextField is tapped date picker will get opened and show the selected date in the TextField.

The following function opens the date picker and return the selected date.

showDatePicker(
              context: context, 
              initialDate:DateTime.now(),
              firstDate:DateTime(1900),
              lastDate: DateTime(2100));

We have to pass this function to the onTap attribute of TextField widget. Thus the date picker appears when the user taps the text input. The attribute readOnly is set as true so that the user doesn’t modify the value using the keyboard. When the date is selected we show the date in TextField using the textfield controller.

Following is the complete flutter example of showing date picker when the textfield is clicked.

import 'package:flutter/material.dart';
void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      home: DatePicker(),
    );
  }
}

class DatePicker extends StatefulWidget {
  DatePicker({Key key}) : super(key: key);

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

class _DatePickerState extends State<DatePicker> {
  final dateController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is removed
    dateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body:Center(child: TextField(
         readOnly: true,
         controller: dateController,
         decoration: InputDecoration(
            hintText: 'Pick your Date'
  ),
         onTap: () async {
        var date =  await showDatePicker(
              context: context, 
              initialDate:DateTime.now(),
              firstDate:DateTime(1900),
              lastDate: DateTime(2100));
        dateController.text = date.toString().substring(0,10);      
       },)),);
  }
}

Following is the output of Flutter date picker example.

I hope this flutter tutorial will help you. Stay tuned for more flutter tutorials and examples.

2 thoughts on “How to Add Date Picker in Flutter”

  1. Pingback: How to Add Time Picker in Flutter – Flutter For You

  2. Pingback: How to Get Current Date in Flutter – Flutter For You

Leave a Comment

Your email address will not be published. Required fields are marked *