Skip to content

Instantly share code, notes, and snippets.

@iam111
Last active February 15, 2024 05:30
Show Gist options
  • Save iam111/27d468d96a981c7297469aa110e59d43 to your computer and use it in GitHub Desktop.
Save iam111/27d468d96a981c7297469aa110e59d43 to your computer and use it in GitHub Desktop.
DatePicker
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTime selectedDate = DateTime.now();
final sDateFormate = "dd/MM/yyyy";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(_formatDate(selectedDate)),
const SizedBox(
height: 20.0,
),
ElevatedButton(
onPressed: () => _selectDate(context),
child: const Text('Select date'),
),
],
),
),
);
}
Future<void> _selectDate(BuildContext context) async {
DateTime currentDate = DateTime.now();
DateTime initialDate = selectedDate ?? currentDate;
DateTime? picked = await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: DateTime(1900),
lastDate: currentDate,
);
if (picked != null) {
setState(() {
selectedDate = picked;
});
}
}
String _formatDate(DateTime date) {
return DateFormat('MM/dd/yyyy').format(date);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment