Flutter has a built-in function named showDatePicker that can help us easily implement a date picker.
Example
Preview:
If you want to format the selected date to make it look better, see this article: 4 Ways to Format DateTime in Flutter.
The complete code with explanations in lib/main.dart:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Flutter Example',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTime? _selectedDate;
void _presentDatePicker() {
// showDatePicker is a pre-made funtion of Flutter
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime.now())
.then((pickedDate) {
// Check if no date is selected
if (pickedDate == null) {
return;
}
setState(() {
// using state so that the UI will be rerendered when date is picked
_selectedDate = pickedDate;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Column(children: [
// Show the Date Picker when this button clicked
ElevatedButton(
onPressed: _presentDatePicker, child: const Text('Select Date')),
// display the selected date
Container(
padding: const EdgeInsets.all(30),
child: Text(
_selectedDate != null
? _selectedDate.toString()
: 'No date selected!',
style: const TextStyle(fontSize: 30),
),
)
]),
);
}
}
Further reading:
- How to implement a Date Range Picker in Flutter
- Working with Time Picker in Flutter (Null Safety)
- Working with Cupertino Date Picker in Flutter
- Flutter: Convert UTC Time to Local Time and Vice Versa
- Dart: Convert Timestamp to DateTime and vice versa
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.