Working with Date and Time Pickers in Flutter

This working with date and time pickers in flutter is posted by seven.srikanth at 5/3/2025 3:27:41 PM



<h1 id="working-with-date-and-time-pickers-in-flutter">Working with Date and Time Pickers in Flutter</h1> <h2 id="image-recommendation-add-a-screenshot-showing-both-the-material-date-picker-and-time-picker-side-by-side-displaying-the-calendar-and-clock-interfaces.include-a-mobile-device-frame-to-show-how-these-pickers-appear-on-an-actual-device-screen.file-name-date_time_pickers.png"><!-- Image recommendation: Add a screenshot showing both the Material date picker and time picker side by side, displaying the calendar and clock interfaces. Include a mobile device frame to show how these pickers appear on an actual device screen. File name: date_time_pickers.png</h2> <p>Date and time pickers are essential UI components in many applications. Whether you're building a calendar app, scheduling system, or simply need to collect date information from users, Flutter provides powerful built-in widgets for date and time selection. This guide will walk you through implementing various date and time pickers in your Flutter app.</p> <h2 id="material-date-picker">Material Date Picker</h2> <p>The Material Design date picker is accessible through the <code>showDatePicker()</code> function. Here's a basic implementation:</p> <pre>Future&lt;void&gt; _selectDate(BuildContext context) async { final DateTime? picked = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2000), lastDate: DateTime(2025), );

if (picked != null) { // Do something with the selected date print(&#39;Selected date: ${picked.toString()}&#39;); } }

// Usage in a widget ElevatedButton( onPressed: () =&gt; _selectDate(context), child: Text(&#39;Select Date&#39;), ) </pre> <h3 id="customizing-the-date-picker">Customizing the Date Picker</h3> <p>You can customize the appearance and behavior of the date picker using additional parameters:</p> <pre>Future&lt;void&gt; _selectDate(BuildContext context) async { final DateTime? picked = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2000), lastDate: DateTime(2025), // Customization options initialEntryMode: DatePickerEntryMode.calendarOnly, selectableDayPredicate: (DateTime day) { // Disable weekends return day.weekday != DateTime.saturday &amp;&amp; day.weekday != DateTime.sunday; }, helpText: &#39;SELECT A DATE&#39;, cancelText: &#39;CANCEL&#39;, confirmText: &#39;OK&#39;, fieldLabelText: &#39;Enter Date&#39;, fieldHintText: &#39;Month/Day/Year&#39;, builder: (context, child) { return Theme( data: ThemeData.light().copyWith( colorScheme: ColorScheme.light( primary: Colors.blue, onPrimary: Colors.white, surface: Colors.blueAccent, onSurface: Colors.black, ), dialogBackgroundColor: Colors.white, ), child: child!, ); }, ); } </pre> <h2 id="material-time-picker">Material Time Picker</h2> <p>For selecting time, Flutter provides the <code>showTimePicker()</code> function:</p> <pre>Future&lt;void&gt; _selectTime(BuildContext context) async { final TimeOfDay? picked = await showTimePicker( context: context, initialTime: TimeOfDay.now(), );

if (picked != null) { // Do something with the selected time print(&#39;Selected time: ${picked.format(context)}&#39;); } }

// Usage in a widget ElevatedButton( onPressed: () =&gt; _selectTime(context), child: Text(&#39;Select Time&#39;), ) </pre> <h3 id="customizing-the-time-picker">Customizing the Time Picker</h3> <p>Similar to the date picker, you can customize the time picker:</p> <pre>Future&lt;void&gt; _selectTime(BuildContext context) async { final TimeOfDay? picked = await showTimePicker( context: context, initialTime: TimeOfDay.now(), // Customization options initialEntryMode: TimePickerEntryMode.input, helpText: &#39;SELECT TIME&#39;, cancelText: &#39;CANCEL&#39;, confirmText: &#39;OK&#39;, hourLabelText: &#39;Hour&#39;, minuteLabelText: &#39;Minute&#39;, builder: (context, child) { return Theme( data: ThemeData.light().copyWith( colorScheme: ColorScheme.light( primary: Colors.green, onPrimary: Colors.white, surface: Colors.greenAccent, onSurface: Colors.black, ), // Button colors buttonTheme: ButtonThemeData( colorScheme: ColorScheme.light( primary: Colors.green, ), ), // Dialog background color dialogBackgroundColor: Colors.white, ), child: child!, ); }, ); } </pre> <h2 id="date-and-time-range-selection">Date and Time Range Selection</h2> <p>Sometimes you need to select a range of dates. Here's how to create a date range picker:</p> <pre>Future&lt;void&gt; _selectDateRange(BuildContext context) async { final DateTimeRange? picked = await showDateRangePicker( context: context, firstDate: DateTime(2000), lastDate: DateTime(2025), initialDateRange: DateTimeRange( start: DateTime.now(), end: DateTime.now().add(Duration(days: 7)), ), );

if (picked != null) { // Do something with the selected date range print(&#39;Date range: ${picked.start.toString()} to ${picked.end.toString()}&#39;); } }

// Usage in a widget ElevatedButton( onPressed: () =&gt; _selectDateRange(context), child: Text(&#39;Select Date Range&#39;), ) </pre> <h2 id="date-formatting">Date Formatting</h2> <p>Working with dates often requires formatting. The <code>intl</code> package is perfect for this:</p> <pre>// Add to pubspec.yaml: // dependencies: // intl: ^0.18.1

import &#39;package:intl/intl.dart&#39;;

// Format a date String formattedDate = DateFormat(&#39;yyyy-MM-dd&#39;).format(DateTime.now()); print(formattedDate); // Output: 2024-06-12

// Format with different patterns print(DateFormat(&#39;EEE, MMM d, y&#39;).format(DateTime.now())); // Wed, Jun 12, 2024 print(DateFormat(&#39;EEEE, MMMM d, y&#39;).format(DateTime.now())); // Wednesday, June 12, 2024 print(DateFormat(&#39;h:mm a&#39;).format(DateTime.now())); // 3:30 PM </pre> <p>Common format patterns:</p> <ul> <li><code>yyyy</code>: 4-digit year (2024)</li> <li><code>yy</code>: 2-digit year (24)</li> <li><code>MM</code>: 2-digit month (06)</li> <li><code>MMM</code>: Short month name (Jun)</li> <li><code>MMMM</code>: Full month name (June)</li> <li><code>d</code>: Day of month (1-31)</li> <li><code>E</code> or <code>EE</code>: Short weekday (Wed)</li> <li><code>EEEE</code>: Full weekday (Wednesday)</li> <li><code>h</code>: Hour in 12-hour format (1-12)</li> <li><code>H</code>: Hour in 24-hour format (0-23)</li> <li><code>mm</code>: Minute (00-59)</li> <li><code>ss</code>: Second (00-59)</li> <li><code>a</code>: AM/PM marker</li> </ul> <h2 id="creating-custom-date-pickers">Creating Custom Date Pickers</h2> <p>Sometimes you need more control over the date picker UI. Here's a simple custom date picker using a <code>CalendarDatePicker</code>:</p> <pre>class CustomDatePicker extends StatefulWidget { final Function(DateTime) onDateSelected; final DateTime initialDate;

const CustomDatePicker({ Key? key, required this.onDateSelected, required this.initialDate, }) : super(key: key);

@override _CustomDatePickerState createState() =&gt; _CustomDatePickerState(); }

class _CustomDatePickerState extends State&lt;CustomDatePicker&gt; { late DateTime _selectedDate;

@override void initState() { super.initState(); _selectedDate = widget.initialDate; }

@override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(12), boxShadow: [ BoxShadow( color: Colors.black12, blurRadius: 10, spreadRadius: 1, ), ], ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( &#39;Select a Date&#39;, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 16), CalendarDatePicker( initialDate: _selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), onDateChanged: (date) { setState(() ); }, ), SizedBox(height: 16), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text(&#39;CANCEL&#39;), ), SizedBox(width: 8), ElevatedButton( onPressed: () { widget.onDateSelected(_selectedDate); Navigator.of(context).pop(); }, child: Text(&#39;OK&#39;), ), ], ), ], ), ); } }

// Usage Future&lt;void&gt; _openCustomDatePicker(BuildContext context) async { await showDialog( context: context, builder: (BuildContext context) { return Dialog( child: CustomDatePicker( initialDate: DateTime.now(), onDateSelected: (date) { print(&#39;Custom picker selected: ${date.toString()}&#39;); }, ), ); }, ); } </pre> <h2 id="working-with-different-time-zones">Working with Different Time Zones</h2> <p>Handling time zones is crucial for many applications. Here's how to work with time zones in Flutter:</p> <pre>// Get current timestamp in UTC DateTime utcNow = DateTime.now().toUtc(); print(&#39;UTC time: $utcNow&#39;);

// Convert from UTC to local time DateTime localTime = utcNow.toLocal(); print(&#39;Local time: $localTime&#39;);

// Create a DateTime with a specific time zone offset DateTime specificTimeZone = DateTime.now().toUtc().add(Duration(hours: -5)); // EST print(&#39;EST time: $specificTimeZone&#39;); </pre> <p>For more advanced time zone handling, consider using packages like <code>timezone</code>.</p> <h2 id="persistent-date-storage">Persistent Date Storage</h2> <p>When storing dates in shared preferences or databases, it's best to use standardized formats:</p> <pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;

// Save date to SharedPreferences Future&lt;void&gt; saveDate(DateTime date) async { final prefs = await SharedPreferences.getInstance(); // Store as ISO 8601 string await prefs.setString(&#39;saved_date&#39;, date.toIso8601String()); }

// Retrieve date from SharedPreferences Future&lt;DateTime?&gt; getSavedDate() async { final prefs = await SharedPreferences.getInstance(); final dateString = prefs.getString(&#39;saved_date&#39;); if (dateString != null) { return DateTime.parse(dateString); } return null; } </pre> <h2 id="building-a-complete-date-and-time-picker">Building a Complete Date and Time Picker</h2> <p>Let's put everything together to create a complete date and time picker with a formatted display:</p> <pre>import &#39;package:flutter/material.dart&#39;; import &#39;package:intl/intl.dart&#39;;

class DateTimePickerWidget extends StatefulWidget { const DateTimePickerWidget({Key? key}) : super(key: key);

@override _DateTimePickerWidgetState createState() =&gt; _DateTimePickerWidgetState(); }

class _DateTimePickerWidgetState extends State&lt;DateTimePickerWidget&gt; { DateTime _selectedDate = DateTime.now(); TimeOfDay _selectedTime = TimeOfDay.now(); final DateFormat _dateFormat = DateFormat(&#39;EEEE, MMMM d, y&#39;);

Future&lt;void&gt; _selectDate(BuildContext context) async { final DateTime? picked = await showDatePicker( context: context, initialDate: _selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2025), );

if (picked != null &amp;amp;&amp;amp; picked != _selectedDate) {
  setState(() {
    _selectedDate = picked;
  });
}

}

Future&lt;void&gt; _selectTime(BuildContext context) async { final TimeOfDay? picked = await showTimePicker( context: context, initialTime: _selectedTime, );

if (picked != null &amp;amp;&amp;amp; picked != _selectedTime) {
  setState(() {
    _selectedTime = picked;
  });
}

}

String get formattedDateTime { // Combine date and time final DateTime combinedDateTime = DateTime( _selectedDate.year, _selectedDate.month, _selectedDate.day, _selectedTime.hour, _selectedTime.minute, );

// Format date and time
final String formattedDate = _dateFormat.format(combinedDateTime);
final String formattedTime = _selectedTime.format(context);

return &amp;#39;$formattedDate at $formattedTime&amp;#39;;

}

@override Widget build(BuildContext context) { return Card( margin: EdgeInsets.all(16), elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), child: Padding( padding: EdgeInsets.all(16), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( &#39;Select Date and Time&#39;, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 16), Text( formattedDateTime, style: TextStyle( fontSize: 16, ), textAlign: TextAlign.center, ), SizedBox(height: 24), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton.icon( onPressed: () =&gt; _selectDate(context), icon: Icon(Icons.calendar_today), label: Text(&#39;Date&#39;), style: ElevatedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12), ), ), ElevatedButton.icon( onPressed: () =&gt; _selectTime(context), icon: Icon(Icons.access_time), label: Text(&#39;Time&#39;), style: ElevatedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12), ), ), ], ), SizedBox(height: 16), ElevatedButton( onPressed: () { // Use the selected date and time final String formattedOutput = formattedDateTime; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(&#39;Selected: $formattedOutput&#39;), duration: Duration(seconds: 3), ), ); }, child: Text(&#39;Confirm Selection&#39;), style: ElevatedButton.styleFrom( minimumSize: Size(double.infinity, 50), ), ), ], ), ), ); } } </pre> <h2 id="best-practices-for-date-and-time-pickers">Best Practices for Date and Time Pickers</h2> <ol> <li><p><strong>Always validate dates</strong>: Ensure selected dates make sense for your application (e.g., don't allow scheduling in the past for future events).</p> </li> <li><p><strong>Consider cultural differences</strong>: Remember that date formats vary by region (MM/DD/YYYY vs DD/MM/YYYY). Use the <code>intl</code> package to handle localization.</p> </li> <li><p><strong>Handle time zones properly</strong>: Be explicit about whether dates are in local time or UTC, especially for applications with users across different time zones.</p> </li> <li><p><strong>Provide clear instructions</strong>: Make it obvious what dates are selectable and in what format they should be entered.</p> </li> <li><p><strong>Consider accessibility</strong>: Ensure date pickers are usable with screen readers and keyboard navigation.</p> </li> <li><p><strong>Include sensible defaults</strong>: Pre-select reasonable dates and times to minimize user effort.</p> </li> <li><p><strong>Offer different entry modes</strong>: Some users prefer typing dates while others prefer calendar selection. Consider supporting both.</p> </li> </ol> <h2 id="conclusion">Conclusion</h2> <p>Flutter provides robust built-in widgets for date and time picking that can be customized to fit your application's design needs. By combining these with proper date formatting and time zone handling, you can create intuitive date and time selection experiences for your users.</p> <p>Whether you're building a scheduling app, a calendar, or any application that deals with dates and times, these tools will help you implement clean and user-friendly date and time picking functionality in your Flutter application.</p>


Tags: flutter,markdown,generated








0 Comments
Login to comment.
Recent Comments