X

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 date time picker integration in your android and iOS apps using flutter.

Flutter Date Time Picker Video Tutorial:

Refer to the tutorial below for a more detailed explanation of the implementation process.

 

Project Structure :

This image illustrates the project structure and implementation of the date-time picker.

 

pubspec.yaml :

Add a dependency flutter_datetime_picker

dependencies:
  flutter:
    sdk: flutter
  flutter_datetime_picker: any

 

 

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: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: 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 :

Below is the complete code for integrating a date-time picker into your flutter app.

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 {
  @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),
    ),
  );
}

 

 

Flutter date time picker output :

This screen demonstrates the implementation of a date time picker.

If you have any questions regarding this tutorial, don’t hesitate to ask in the comments section below. If you found it helpful, please consider liking and sharing for further updates.

abhishek:
Related Post

This website uses cookies.