Date and Date Picker In Flutter
DatePicker is a material widget in a flutter that lets the user select a date. Since there is no widget available for creating a date picker we will use the showDatePicker() function.
It will display a Material Design date picker in a dialog by calling flutter’s inbuilt function. We will use it in instances like booking a movie ticket, train ticket, etc.
A date picker is a helpful addition to your UI, making it easy for app users to select dates from a calendar. Whether you’re adding a date of birth field to a registration form or offering time slots for users to book an appointment, you can use a date picker library to simplify the process.
Date format =https://stackoverflow.com/questions/16126579/how-do-i-format-a-date-with-dart
Lets Start Implementation
Add Package
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(MyAppNew());
}
class MyAppNew extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyApp(),
);
}
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
DateTime? date;
String formatDate(DateTime date) => DateFormat("MMMM d").format(date);
TimeOfDay selectedTime = TimeOfDay.now();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(date != null ? DateFormat.yMMMMd().format(date!) : ""),
TextButton(
onPressed: () {
print('enter');
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime.now())
.then((value) {
setState(() {
date = value!;
});
});
},
child: Text('Choose Date'),
),
SizedBox(height: 10,),
ElevatedButton(
onPressed: () {
_selectTime(context);
},
child: Text("Choose Time"),
),
SizedBox(height: 10,),
Text("${selectedTime.hour}:${selectedTime.minute}"),
],
),
),
),
);
}
_selectTime(BuildContext context) async {
final TimeOfDay? timeOfDay = await showTimePicker(
context: context,
initialTime: selectedTime,
initialEntryMode: TimePickerEntryMode.dial,
);
if(timeOfDay != null && timeOfDay != selectedTime)
{
setState(() {
selectedTime = timeOfDay;
});
}
}
}
Comments
Post a Comment