Flutter Date & Time Picker Example

Flutter Date & Time Picker Example:

Date/Time picker FormFields:

Here we are using Two Flutter widgets that wrap a TextFormField and integrates the date and/or time picker dialogs.

DateTimePickerFormField:

For using the date picker and optionally the time picker too. It shows DateTime values.

This widget is used to pick the date along with the time of the Date:

TimePickerFormField:

This widget is used to pick the Time of the Day. means we only wrap time values only.

To use above to widgets in Flutter we need to add its dependencies first.

Adding the dependency package:

Add this package’s pubspec.yaml file by using below code:

dependencies:

datetime_picker_formfield: ^0.1.4

Install the  dependency package from the terminal Editor:

You can install packages from the command line with Flutter use the below code to install the package into flutter :

$ flutter packages get

 

Import the package into the flutter Dart code :

By using below code we are importing the package into the Dart code towritr the Dart code for time and date picker form. without importing the package it will shows error or exception that is package nor found exception.

importpackage:datetime_picker_formfield/datetime_picker_formfield.dart';

Below is the sample code for Date and time pickup for a given form fields:

 

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:datetime_picker_formfield/time_picker_formfield.dart';

const appName = 'DateTimePickerFormField Example';

void main() => runApp(MaterialApp(
title: appName,
home: MyHomePage(),
theme: ThemeData.light().copyWith(
inputDecorationTheme:
InputDecorationTheme(border: OutlineInputBorder())),
));

class MyHomePage extends StatefulWidget {
@override
MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
final dateFormat = DateFormat("EEEE, MMMM d, yyyy 'at' h:mma");
final timeFormat = DateFormat("h:mm a");
DateTime date;
TimeOfDay time;
@override

Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(appName)),
body: Padding(
padding: EdgeInsets.all(16.0),
child: ListView(
children: <Widget>[
DateTimePickerFormField(
format: dateFormat,
decoration: InputDecoration(labelText: 'Date'),
onChanged: (dt) => setState(() => date = dt),
),

SizedBox(height: 16.0),
TimePickerFormField(
format: timeFormat,
decoration: InputDecoration(labelText: 'Time'),
onChanged: (t) => setState(() => time = t),
),

SizedBox(height: 16.0),
Text('date.toString(): $date', style: TextStyle(fontSize: 18.0)),
SizedBox(height: 16.0),
Text('time.toString(): $time', style: TextStyle(fontSize: 18.0)),
],
),
));
}

Leave a Reply

Categories