date_picker.dart 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import 'package:calendar_date_picker2/calendar_date_picker2.dart';
  2. import 'package:date_format/date_format.dart';
  3. import 'package:flutter/material.dart';
  4. class VDatePicker extends StatefulWidget {
  5. final DateTime? value;
  6. final ValueChanged<DateTime>? onChanged;
  7. const VDatePicker({super.key, this.value, this.onChanged});
  8. @override
  9. State<StatefulWidget> createState() => _DatePickerState();
  10. }
  11. class _DatePickerState extends State<VDatePicker> {
  12. late DateTime currentDate;
  13. @override
  14. void initState() {
  15. if (widget.value == null) {
  16. final now = DateTime.now();
  17. currentDate = DateTime(now.year, now.month, now.day);
  18. } else {
  19. currentDate = widget.value!;
  20. }
  21. super.initState();
  22. }
  23. @override
  24. Widget build(BuildContext context) {
  25. final dateStr = formatDate(currentDate, ["yyyy", "-", "mm", "-", "dd"]);
  26. return Material(
  27. child: Ink(
  28. child: InkWell(
  29. onTap: () async {
  30. var results = await showCalendarDatePicker2Dialog(
  31. context: context,
  32. config: CalendarDatePicker2WithActionButtonsConfig(
  33. calendarType: CalendarDatePicker2Type.single,
  34. ),
  35. dialogBackgroundColor: Colors.white,
  36. dialogSize: const Size(325, 400),
  37. value: [
  38. currentDate,
  39. ],
  40. borderRadius: BorderRadius.circular(4),
  41. );
  42. if (results != null &&
  43. results.isNotEmpty &&
  44. results.first != null) {
  45. setState(() {
  46. currentDate = results.first!;
  47. widget.onChanged?.call(currentDate);
  48. });
  49. }
  50. },
  51. child: Container(
  52. // height: 38,
  53. alignment: Alignment.centerLeft,
  54. padding: const EdgeInsets.symmetric(horizontal: 8),
  55. decoration: BoxDecoration(
  56. border: Border.all(color: Colors.grey),
  57. borderRadius: BorderRadius.zero,
  58. ),
  59. child: Row(
  60. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  61. children: [
  62. Text(
  63. dateStr,
  64. style: const TextStyle(color: Colors.black, fontSize: 16),
  65. ),
  66. const Icon(
  67. Icons.calendar_month_outlined,
  68. color: Colors.grey,
  69. size: 18,
  70. ),
  71. ],
  72. ),
  73. ),
  74. ),
  75. ),
  76. );
  77. }
  78. }