fahimkamal63

Time and Date Picker Flutter

Dec 9th, 2021
922
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import 'package:flutter/material.dart';
  2.  
  3. class DateAndTimePicker extends StatefulWidget {
  4.   const DateAndTimePicker({Key? key}) : super(key: key);
  5.  
  6.   @override
  7.   _DateAndTimePickerState createState() => _DateAndTimePickerState();
  8. }
  9.  
  10. class _DateAndTimePickerState extends State<DateAndTimePicker> {
  11.   DateTime? pickDate;
  12.   TimeOfDay? pickTime;
  13.  
  14.   @override
  15.   void initState() {
  16.     super.initState();
  17.     pickDate = DateTime.now();
  18.     pickTime = TimeOfDay.now();
  19.   }
  20.  
  21.   void _pickedTime() async {
  22.     TimeOfDay? time = await showTimePicker(
  23.         initialEntryMode: TimePickerEntryMode.input,
  24.         context: context,
  25.         initialTime: pickTime!);
  26.  
  27.     if (time != null) {
  28.       setState(() {
  29.         pickTime = time;
  30.       });
  31.     }
  32.   }
  33.  
  34.   void _pickedDate() async {
  35.     DateTime? date = await showDatePicker(
  36.         context: context,
  37.         initialDate: pickDate!,
  38.         firstDate: DateTime(DateTime.now().year - 10),
  39.         lastDate: DateTime(DateTime.now().year + 10));
  40.  
  41.     if (date != null) {
  42.       setState(() {
  43.         pickDate = date;
  44.       });
  45.     }
  46.   }
  47.  
  48.   @override
  49.   Widget build(BuildContext context) {
  50.     return Scaffold(
  51.       appBar: AppBar(
  52.         title: Text("Date & Time Picker"),
  53.         centerTitle: true,
  54.       ),
  55.       body: Column(
  56.         children: [
  57.           Center(
  58.             child: ListTile(
  59.               title: Text(
  60.                 'Date: ${pickDate!.day} : ${pickDate!.month} : ${pickDate!.year}',
  61.                 style: TextStyle(fontSize: 50),
  62.               ),
  63.               trailing: IconButton(
  64.                   onPressed: _pickedDate,
  65.                   icon: Icon(
  66.                     Icons.calendar_today_outlined,
  67.                     size: 30,
  68.                   )),
  69.             ),
  70.           ),
  71.           Center(
  72.             child: ListTile(
  73.               title: Text(
  74.                 'Time: ${pickTime!.format(context)}',
  75.                 style: TextStyle(fontSize: 30),
  76.               ),
  77.               trailing: IconButton(
  78.                   onPressed: _pickedTime,
  79.                   icon: Icon(
  80.                     Icons.access_time_outlined,
  81.                     size: 30,
  82.                   )),
  83.             ),
  84.           )
  85.         ],
  86.       ),
  87.     );
  88.   }
  89. }
  90.  
RAW Paste Data