DatePicker in Flutter
In this tutorial, you will learn how to use DatePicker in Flutter with the built-in showDatePicker function. The picker returns a DateTime object that you can format and display in your UI.
The example below shows a screen with a ListTile containing a calendar icon. Tapping the icon opens the Material date picker and updates the tile with the selected date formatted as dd-MM-yyyy.
Screenshots
Flutter Source Code
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyDateTutorial(),
title: "Date Picker Tutorial",
));
}
class MyDateTutorial extends StatefulWidget {
@override
_MyFieldTutorialState createState() => _MyFieldTutorialState();
}
class _MyFieldTutorialState extends State<MyDateTutorial> {
String selecteddate = "Select Date";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Date Picker Tutorial"),
),
body: Container(
child: Column(
children: [
ListTile(
title: Text("$selecteddate"),
trailing: IconButton(
icon: Icon(
Icons.date_range,
color: Colors.red,
),
onPressed: () {
getshowDatePicker().then((value) {
if (value != null) {
setState(() {
var date = DateTime.parse(value.toString());
selecteddate = "${date.day}-${date.month}-${date.year}";
});
}
});
},
),
),
],
),
),
);
}
Future getshowDatePicker() async {
var selected = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2050),
);
return selected;
}
}
Frequently Asked Questions
What is showDatePicker in Flutter?
showDatePicker is a built-in Flutter function that opens a Material Design date picker dialog and returns a DateTime object representing the selected date, or null if the user cancels.
How do I format a date in Flutter?
You can format a DateTime manually by reading its day, month, and year properties, or use the intl package with DateFormat('dd-MM-yyyy').format(date) for locale-aware formatting.
What are firstDate and lastDate in showDatePicker?
firstDate is the earliest selectable date and lastDate is the latest selectable date in the picker. The user cannot scroll or select dates outside this range.
How do I restrict the picker to future dates only in Flutter?
Set firstDate: DateTime.now() so past dates are disabled. To allow only past dates, set lastDate: DateTime.now() instead.
Does showDatePicker work on both Android and iOS?
Yes. showDatePicker renders the Material Design date picker on both Android and iOS by default. On iOS, it appears with Material styling rather than the native Cupertino picker.
Conclusion
In this tutorial, you learned how to implement a DatePicker in Flutter using the built-in showDatePicker function. You used DateTime.now() as the initial date, restricted the range with firstDate and lastDate, and formatted the selected date as dd-MM-yyyy.
Related topics: Flutter TimePicker, Flutter Material Dialogs, DateTime Formatting, Flutter Stateful Widgets, Flutter ListTile, Flutter IconButton