Flutter Date Time Picker Tutorial for Beginners

 

Flutter Date Time Picker :

Flutter Date Time Picker is used to set the date and time according to the format so that we can maintain the uniqueness between the date format stored.

We can show a picker and ask user to select the date and store them according to 12 hour and 24 hour format depending upon the user requirement.

Date and time is almost used in every app where there is a need to provide some service to the user like booking train, bus, air tickets and also movie tickets so on.

Also you can create apps that can store your daily records based on the dates, analytic apps, news papers and more apps are based on this date and time.

In this part of the tutorial we will be dealing with flutter date time picker integration in your android and iOS apps using flutter.

Flutter Date Time Picker Video Tutorial:

Go through the below tutorial for more details on implementation.

 

Project Structure :

This image shows the project structure and implementation for flutter date time picker

flutter date time picker

 

pubspec.yaml :

Add a dependency flutter_datetime_picker

dependencies:
  flutter:
    sdk: flutter
  flutter_datetime_picker:

 

main.dart :

Initialize the program with void main() and consider default MyApp()

void main() => runApp(new MyApp());

 

Return a MaterialApp and provide theme

MaterialApp(
  title: 'Flutter Demo',
  theme: new ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: new HomePage(),
);

 

Declare variables date time and boolean to check whether button is pressed or not.

DateTime selectedDateTime ;
bool pressed = false;

 

Add a FlatButton and set Text “Select Date Time

FlatButton(
    onPressed: () {
      setState((){
        pressed = true;

        DatePicker.showTime12hPicker(context, showTitleActions: true, onChanged: (date) {
        print('change $date in time zone ' + date.timeZoneOffset.inHours.toString());
      }, onConfirm: (date) {
      selectedDateTime = date;
      }, currentTime: DateTime(2008, 12, 31, 23, 12, 34));
      });
    },
    child: Text(
      'Select Date Time',
      style: TextStyle(color: Colors.blue,fontSize: 20),
    )),

 

Now we need to add a SizedBox so that we have some space in between widgets

SizedBox(height: 50),

 

Now display the picker when condition is true

pressed ? _displayDateTime(selectedDateTime): SizedBox(),

 

Add a widget displayDateTime which will display selected Date and Time

Widget _displayDateTime(selectedDateTime) {
  return Center(
    child: Text("Selected  $selectedDateTime",style: TextStyle(fontSize: 15),)
  );

}

 

Add a Custom Picker which accepts DateTime and LocaleType

CustomPicker({DateTime currentTime, LocaleType locale}) : super(locale: locale) {
  this.currentTime = currentTime ?? DateTime.now();
  this.setLeftIndex(this.currentTime.hour);
  this.setMiddleIndex(this.currentTime.minute);
  this.setRightIndex(this.currentTime.second);
}

 

Add the wheels left, middle and right.

@override
String leftStringAtIndex(int index) {
  if (index >= 0 && index < 24) {
    return this.digits(index, 2);
  } else {
    return null;
  }
}

@override
String middleStringAtIndex(int index) {
  if (index >= 0 && index < 60) {
    return this.digits(index, 2);
  } else {
    return null;
  }
}

@override
String rightStringAtIndex(int index) {
  if (index >= 0 && index < 60) {
    return this.digits(index, 2);
  } else {
    return null;
  }
}

 

Add Dividers

@override
String leftDivider() {
  return "|";
}

@override
String rightDivider() {
  return "|";
}

 

Specify the layout proportions

@override
List<int> layoutProportions() {
  return [1, 2, 1];
}

 

 

@override
DateTime finalTime() {
  return currentTime.isUtc
      ? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
      this.currentLeftIndex(), this.currentMiddleIndex(), this.currentRightIndex())
      : DateTime(currentTime.year, currentTime.month, currentTime.day, this.currentLeftIndex(),
      this.currentMiddleIndex(), this.currentRightIndex());
}

 

FullCode :

Providing the full code for flutter date time picker integration

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

void main() => runApp(new MyApp());

class CustomPicker extends CommonPickerModel {
  String digits(int value, int length) {
    return '$value'.padLeft(length, "0");
  }

  CustomPicker({DateTime currentTime, LocaleType locale}) : super(locale: locale) {
    this.currentTime = currentTime ?? DateTime.now();
    this.setLeftIndex(this.currentTime.hour);
    this.setMiddleIndex(this.currentTime.minute);
    this.setRightIndex(this.currentTime.second);
  }

  @override
  String leftStringAtIndex(int index) {
    if (index >= 0 && index < 24) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String middleStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String rightStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String leftDivider() {
    return "|";
  }

  @override
  String rightDivider() {
    return "|";
  }

  @override
  List<int> layoutProportions() {
    return [1, 2, 1];
  }

  @override
  DateTime finalTime() {
    return currentTime.isUtc
        ? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
        this.currentLeftIndex(), this.currentMiddleIndex(), this.currentRightIndex())
        : DateTime(currentTime.year, currentTime.month, currentTime.day, this.currentLeftIndex(),
        this.currentMiddleIndex(), this.currentRightIndex());
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {

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

class _HomePageState extends State<HomePage> {

  DateTime selectedDateTime ;
  bool pressed = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Datetime Picker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            FlatButton(
                onPressed: () {
                  setState((){
                    pressed = true;

                    DatePicker.showTime12hPicker(context, showTitleActions: true, onChanged: (date) {
                    print('change $date in time zone ' + date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                  selectedDateTime = date;
                  }, currentTime: DateTime(2008, 12, 31, 23, 12, 34));
                  });
                },
                child: Text(
                  'Select Date Time',
                  style: TextStyle(color: Colors.blue,fontSize: 20),
                )),

            SizedBox(height: 50),

            pressed ? _displayDateTime(selectedDateTime): SizedBox(),


          ],
        ),
      ),
    );
  }
}

Widget _displayDateTime(selectedDateTime) {
  return Center(
    child: Text("Selected  $selectedDateTime",style: TextStyle(fontSize: 15),)
  );

}

 

Output :

This screen show the implementation of flutter date time picker

flutter date time picker

If you have any queries do let me know in the comment section below.

Show Buttons
Hide Buttons
Read previous post:
Flutter Calendar Implementation Tutorial

  Flutter Calendar : Flutter tutorial on calendar let you code a calendar where you can mark events make user...

Close