|
| 1 | +import 'package:flutter/material.dart'; |
| 2 | +import 'package:intl/intl.dart'; |
| 3 | + |
| 4 | +class MaterialExamplePage extends StatefulWidget { |
| 5 | + const MaterialExamplePage({super.key}); |
| 6 | + |
| 7 | + @override |
| 8 | + State<MaterialExamplePage> createState() => _MaterialExamplePageState(); |
| 9 | +} |
| 10 | + |
| 11 | +class _MaterialExamplePageState extends State<MaterialExamplePage> { |
| 12 | + DateTime dateTime = DateTime.now(); |
| 13 | + |
| 14 | + Future<DateTime?> pickDate() => showDatePicker(context: context, initialDate: dateTime, firstDate: DateTime(1900), lastDate: DateTime(2100)); |
| 15 | + |
| 16 | + Future<TimeOfDay?> pickTime() => showTimePicker(context: context, initialTime: TimeOfDay(hour: dateTime.hour, minute: dateTime.minute)); |
| 17 | + |
| 18 | + @override |
| 19 | + Widget build(BuildContext context) { |
| 20 | + return Container( |
| 21 | + child: Padding( |
| 22 | + padding: const EdgeInsets.only(right: 8.0, left: 8.0), |
| 23 | + child: Column( |
| 24 | + mainAxisAlignment: MainAxisAlignment.center, |
| 25 | + children: [ |
| 26 | + Row( |
| 27 | + mainAxisAlignment: MainAxisAlignment.center, |
| 28 | + children: [ |
| 29 | + Text( |
| 30 | + DateFormat('yyyy-MM-dd').format(dateTime), |
| 31 | + style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold), |
| 32 | + ), |
| 33 | + Text( |
| 34 | + DateFormat(' kk:mm').format(dateTime), |
| 35 | + style: const TextStyle(fontSize: 30), |
| 36 | + ), |
| 37 | + ], |
| 38 | + ), |
| 39 | + Padding( |
| 40 | + padding: const EdgeInsets.only(top: 16.0), |
| 41 | + child: Row( |
| 42 | + mainAxisAlignment: MainAxisAlignment.spaceEvenly, |
| 43 | + children: [ |
| 44 | + ElevatedButton( |
| 45 | + child: const Text("Date", style: TextStyle(fontSize: 20),), |
| 46 | + onPressed: () async { |
| 47 | + final newDate = await pickDate(); |
| 48 | + if (newDate == null) return; // person pressed 'CANCEL' |
| 49 | + |
| 50 | + // Update datetime object that's shown with new date |
| 51 | + final newDateTime = DateTime(newDate.year, newDate.month, newDate.day, dateTime.hour, dateTime.minute); |
| 52 | + setState( |
| 53 | + () => dateTime = newDateTime, |
| 54 | + ); |
| 55 | + }), |
| 56 | + ElevatedButton( |
| 57 | + child: const Text("Time", style: TextStyle(fontSize: 20),), |
| 58 | + onPressed: () async { |
| 59 | + final newTime = await pickTime(); |
| 60 | + if (newTime == null) return; // person pressed 'CANCEL' |
| 61 | + |
| 62 | + // Update datetime object that's shown with new time |
| 63 | + final newDateTime = DateTime(dateTime.year, dateTime.month, dateTime.day, newTime.hour, newTime.minute); |
| 64 | + setState( |
| 65 | + () => dateTime = newDateTime, |
| 66 | + ); |
| 67 | + }) |
| 68 | + ], |
| 69 | + ), |
| 70 | + ) |
| 71 | + ], |
| 72 | + ), |
| 73 | + ), |
| 74 | + ); |
| 75 | + } |
| 76 | +} |
0 commit comments