DEV Community

Kingsley Okafor
Kingsley Okafor

Posted on • Edited on

Implement flutter Date Picker

What is a Date Picker?

A Date Picker widget allows users to easily select date in a specified format. The Date Picker provides day, month and year view options to quickly navigate to the desired date. The Date Picker control makes it easy to work with dates because it handles a lot of the data validation automatically.

As a developer base on your project requirement, you might be required to add the date picker widget to your project.

Prerequisite

To complete this tutorial, you will need:

  • To download and install Flutter.
  • To download and install Android Studio or Visual Studio Code. Android Studio offers an integrated, feature-rich IDE with support for Flutter. Visual Studio Code offers more lightweight, but functional support.
  • It is recommended to install this plugins for your code editor:
    • Flutter and Dart plugins installed for Android Studio.
    • Flutter extension installed for Visual Studio Code.

Step 1 - Setting Up the Project

In order to follow along with the setup, you will be creating a new Flutter app project.

Once you have your environment set up for Flutter, you can run the following to create a new application:

C:\Users\PC>flutter create flutter_date_picker
Enter fullscreen mode Exit fullscreen mode

Navigate to the new project directory and open with vscode:

Open lib/main.dart and replace the contents of lib/main.dart with the following code snippet

import 'package:flutter/material.dart';
import 'ui_home.dart';


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Flutter APP",
      theme: ThemeData(primarySwatch: Colors.blue),
      home:Homepage() ,
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2 - Adding the TextField Widget

Create a new dart file ui_home.dart in the lib directory replace the contents of lib/ui_home.dart with the following code snippet

import 'package:flutter/material.dart';

class Homepage extends StatefulWidget {
  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {
  TextEditingController textController;

  @override
  void initState() {
    super.initState();
    textController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    textController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Flutter APP")),
      body: Container(
        padding: EdgeInsets.all(10),
        child: TextFormField(
          controller: textController,
          onTap: () {},
          decoration: const InputDecoration(
            border: OutlineInputBorder(),
            labelText:'Start Date',
            hintText:"Start Date",
          ),
        ),
      ),
    );
  }

}
Enter fullscreen mode Exit fullscreen mode

Step 3 - Creating the calendar function

Here we created a function pickDate that will show the calendar widget in the date format that we want.

Future pickDate(BuildContext context) async{
    final initialDate = DateTime.now();
    final newDate = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: DateTime(DateTime.now().year -5),
        lastDate: DateTime(DateTime.now().year + 5)
    );
    if (newDate == null) return;
    setState(() {
      textController.text = '${newDate.day}/${newDate.month}/${newDate.year}';
    });
  }
Enter fullscreen mode Exit fullscreen mode

Step 4 - Displaying

Next, Here we added the pickdate function to the onclick event of the textfield widget we created earlier.

import 'package:flutter/material.dart';

class Homepage extends StatefulWidget {
  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {
  TextEditingController textController;

  @override
  void initState() {
    super.initState();
    textController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    textController.dispose();
  }

  Future pickDate(BuildContext context) async{
    final initialDate = DateTime.now();
    final newDate = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: DateTime(DateTime.now().year -5),
        lastDate: DateTime(DateTime.now().year + 5)
    );
    if (newDate == null) return;
    setState(() {
      textController.text = '${newDate.day}/${newDate.month}/${newDate.year}';
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Flutter APP")),
      body: Container(
        padding: EdgeInsets.all(10),
        child: TextFormField(
          controller: textController,
          onTap: () {
            pickDate(context);
          },
          decoration: const InputDecoration(
            border: OutlineInputBorder(),
            labelText:'Start Date',
            hintText:"Start Date",
          ),
        ),
      ),
    );
  }

}
Enter fullscreen mode Exit fullscreen mode

Compile your code and have it run in an emulator:

Image description

Conclusion

In this tutorial we were able to showcase how to implement the date picker widget in flutter. I hope this was helpful.

Top comments (0)