当前位置:   article > 正文

Flutter之日期选择器 calendar_date_picker2_flutter 日期选择器

flutter 日期选择器
calendar_date_picker2主要由两个小部件组成:

1、CalendarDatePicker2,此小部件仅包含日历 UI,并且每当用户点击不同的日期时就会发出事件。

2、CalendarDatePicker2WithActionButtons,此小部件包括日历 UI 和操作按钮(取消和确定)。仅当用户点击“确定”按钮时,此小部件才会发出更新的值。

特点: 
  • 扩展CalendarDatePicker允许nullinitialDate
  • 高度可定制的用户界面
  • 支持三种模式:单一、多重和范围
  • 内置showCalendarDatePicker2Dialog
  • 多语言支持
CalendarDatePicker2参数
ArgumentTypeDescription
configCalendarDatePicker2Config

Calendar UI related configurations

(日历UI的相关配置)

valueList<DateTime?>

The selected [DateTime]s that the picker should display.

(选择器应显示的所选日期)

onValueChangedValueChanged<List<DateTime?>>?

Called when the selected dates changed

(当所选日期更改时的回调函数)

displayedMonthDateDateTime?

Date to control calendar displayed month

(控制日历显示月份的日期)

onDisplayedMonthChangedValueChanged<DateTime>?

The initially displayed view of the calendar picker

(日历选取器的初始显示视图)

 CalendarDatePicker2Config的参数
OptionTypeDescription
calendarTypeCalendarDatePicker2Type?

Calendar picker type, has 3 values: single, multi, range

(日历选择器类型,有3个值:single、multi、range)

firstDateDateTime?

The earliest allowable DateTime user can select

(用户可以选择的最早允许的 DateTime)

lastDateDateTime?

The latest allowable DateTime user can select

(用户可以选择最新允许的DateTime)

currentDateDateTime?

The DateTime representing today which will be outlined in calendar

(用户当前选择的时间)

calendarViewModeDatePickerMode?

The initially displayed view of the calendar picker

(日历选择器最初显示的视图)

weekdayLabelsList<String>?

Custom weekday labels, should starts with Sunday

(自定义工作日标签,应从星期日开始)

weekdayLabelTextStyleTextStyle?

Custom text style for weekday labels

(工作日标签的自定义文本样式)

firstDayOfWeekint?

Index of the first day of week, where 0 points to Sunday, and 6 points to Saturday.

(一周的第一天,0表示周日,6表示周六)

controlsHeightdouble?

Custom height for calendar control toggle's height

(日历控件切换高度的自定义高度)

lastMonthIconWidget?

Custom icon for last month button control

(上个月按钮控件的自定义图标)

nextMonthIconWidget?

Custom icon for next month button control

(下个月按钮控件的自定义图标)

controlsTextStyleTextStyle?

Custom text style for calendar mode toggle control

(日历模式切换控件的自定义文本样式)

dayTextStyleTextStyle?

Custom text style for calendar day text

(日历模式切换控件的自定义文本样式)

selectedDayTextStyleTextStyle?

Custom text style for selected calendar day text

(选定日历日文本的自定义文本样式)

selectedRangeDayTextStyleTextStyle?

Custom text style for selected range calendar day(s)

(选定范围日历日的自定义文本样式)

selectedDayHighlightColorColor?

The highlight color selected day

(所选日期的突出显示颜色)

selectedRangeHighlightColorColor?

The highlight color for day(s) included in the selected range

(所选范围内包含的日期的突出显示颜色)

disabledDayTextStyleTextStyle?

Custom text style for disabled calendar day(s)

(禁用日历日的自定义文本样式)

todayTextStyleTextStyle?Custom text style for current calendar day
(当前日历日的自定义文本样式)
yearTextStyleTextStyle?

Custom text style for years list

(年份列表的自定义文本样式)

selectedYearTextStyleTextStyle?

Custom text style for selected year

(选定年份的自定义文本样式)

dayBorderRadiusBorderRadius?

Custom border radius for day indicator

(日期指示器的自定义边框半径)

yearBorderRadiusBorderRadius?

Custom border radius for year indicator

(年份指示器的自定义边框半径)

selectableDayPredicateSelectableDayPredicate?

Function to provide full control over which dates in the calendar can be selected

(提供对日历中可以选择的日期的完全控制的功能)

dayTextStylePredicateCalendarDayTextStylePredicate?

Function to provide full control over calendar days text style

(提供对日历日文本样式的完全控制的功能)

dayBuilderCalendarDayBuilder?Function to provide full control over day widget UI
(构造日选择部件UI)
yearBuilderCalendarYearBuilder?

Function to provide full control over year widget UI

(构造年份选择部件UI)

disableModePickerbool?

Flag to disable mode picker and hide the toggle icon

(标记以禁用模式选择器并隐藏切换图标)

centerAlignModePickerbool?

Flag to centralize year and month text label in controls

(用于在控件中集中年份和月份文本标签的标志)

customModePickerIconWidget?Custom icon for the mode picker button icon
(模式选择器按钮图标的自定义图标)
modePickerTextHandlerCalendarModePickerTextHandler?

Function to control mode picker displayed text

(控制模式选择器显示文本的函数)

 CalendarDatePicker2WithActionButtonsConfig 除上面的配置外还有其余9个额外的选项
OptionTypeDescription
gapBetweenCalendarAndButtonsdouble?

The gap between calendar and action buttons

(日历和操作按钮之间的间隙)

cancelButtonTextStyleTextStyle?

Text style for cancel button

(取消按钮的文本样式)

cancelButtonWidget?

Custom cancel button

(自定义取消按钮)

okButtonTextStyleTextStyle?

Text style for ok button

(确定按钮的文本样式)

okButtonWidget?

Custom ok button

(自定义确定按钮)

openedFromDialogbool?

Is the calendar opened from dialog

(日历是从对话框打开的吗)

closeDialogOnCancelTappedbool?

Close dialog after user taps the CANCEL button

(用户点击取消按钮后关闭对话框?)

closeDialogOnOkTappedbool?

Close dialog after user taps the OK button

(用户点击确定按钮后关闭对话框?)

buttonPaddingEdgeInsets?

Custom wrapping padding for Ok & Cancel buttons

(用于“确定”和“取消”按钮的自定义包装填充)

使用步骤:

1、 添加依赖

  1. dependencies:
  2. calendar_date_picker2: ^0.5.2
写在前面的_getValueText,用于修改日期格式
  1. String _getValueText(CalendarDatePicker2Type datePickerType, List<DateTime?> values,) {
  2. values = values.map((e) => e != null ? DateUtils.dateOnly(e) : null).toList();
  3. var valueText = (values.isNotEmpty ? values[0] : null).toString().replaceAll('00:00:00.000', '');
  4. if (datePickerType == CalendarDatePicker2Type.multi) {
  5. valueText = values.isNotEmpty ? values.map((v) => v.toString().replaceAll('00:00:00.000', '')).join(', ') : 'null';
  6. }
  7. else if (datePickerType == CalendarDatePicker2Type.range) {
  8. if (values.isNotEmpty) {
  9. final startDate = values[0].toString().replaceAll('00:00:00.000', '');
  10. final endDate = values.length > 1 ? values[1].toString().replaceAll('00:00:00.000', '') : 'null';
  11. valueText = '$startDate to $endDate';
  12. }
  13. else {
  14. return 'null';
  15. }
  16. }
  17. return valueText;
  18. }
对话框模式

调用 showCalendarDatePicker2Dialog 其中包含的必选参数:dialogSize、config、context

  1. //工作日文本样式
  2. const dayTextStyle = TextStyle(color: Colors.black, fontWeight: FontWeight.w700);
  3. //周末文本样式
  4. final weekendTextStyle = TextStyle(color: Colors.grey[500], fontWeight: FontWeight.w600);
  5. //与当前日期相同的日期
  6. final anniversaryTextStyle = TextStyle(
  7. color: Colors.red[400],
  8. fontWeight: FontWeight.w700,
  9. decoration: TextDecoration.underline,
  10. );
  11. final config = CalendarDatePicker2WithActionButtonsConfig(
  12. //日文本样式
  13. dayTextStyle: dayTextStyle,
  14. //日期选择器类型——范围
  15. calendarType: CalendarDatePicker2Type.range,
  16. //所选日期的突出显示颜色
  17. selectedDayHighlightColor: Colors.purple[800],
  18. //用户点击取消按钮后关闭对话框
  19. closeDialogOnCancelTapped: true,
  20. //一周的第一天,0表示周日,6表示周六
  21. firstDayOfWeek: 1,
  22. //工作日标签的自定义文本样式
  23. weekdayLabelTextStyle: const TextStyle(
  24. color: Colors.black87,
  25. fontWeight: FontWeight.bold,
  26. ),
  27. //日历模式切换控件的自定义文本样式
  28. controlsTextStyle: const TextStyle(
  29. color: Colors.black,
  30. fontSize: 15,
  31. fontWeight: FontWeight.bold,
  32. ),
  33. //用于在控件中集中年份和月份文本标签的标志
  34. centerAlignModePicker: true,
  35. //模式选择器按钮图标的自定义图标
  36. customModePickerIcon: const SizedBox(),
  37. //选定日历日文本的自定义文本样式
  38. selectedDayTextStyle: dayTextStyle.copyWith(color: Colors.white),
  39. //提供对日历日文本样式的完全控制的功能
  40. dayTextStylePredicate: ({required date}) {
  41. TextStyle? textStyle;
  42. if (date.weekday == DateTime.saturday ||
  43. date.weekday == DateTime.sunday) {
  44. textStyle = weekendTextStyle;
  45. }
  46. /*if (DateUtils.isSameDay(date, DateTime(2021, 1, 25))) {
  47. textStyle = anniversaryTextStyle;
  48. }*/
  49. if (DateUtils.isSameDay(date, DateTime.now())) {
  50. textStyle = anniversaryTextStyle;
  51. }
  52. return textStyle;
  53. },
  54. //构造日部件UI
  55. dayBuilder: ({required date, textStyle, decoration, isSelected, isDisabled, isToday,}) {
  56. Widget? dayWidget;
  57. if (date.day % 3 == 0 && date.day % 9 != 0) {
  58. dayWidget = Container(
  59. decoration: decoration,
  60. child: Center(
  61. child: Stack(
  62. alignment: AlignmentDirectional.center,
  63. children: [
  64. Text(
  65. MaterialLocalizations.of(context).formatDecimal(date.day),
  66. style: textStyle,
  67. ),
  68. Padding(
  69. padding: const EdgeInsets.only(top: 27.5),
  70. child: Container(
  71. height: 4,
  72. width: 4,
  73. decoration: BoxDecoration(
  74. borderRadius: BorderRadius.circular(5),
  75. color: isSelected == true
  76. ? Colors.white
  77. : Colors.grey[500],
  78. ),
  79. ),
  80. ),
  81. ],
  82. ),
  83. ),
  84. );
  85. }
  86. return dayWidget;
  87. },
  88. //构造年份选择部件
  89. yearBuilder: ({required year, decoration, isCurrentYear, isDisabled, isSelected, textStyle,}) {
  90. return Center(
  91. child: Container(
  92. decoration: decoration,
  93. height: 36,
  94. width: 72,
  95. child: Center(
  96. child: Semantics(
  97. selected: isSelected,
  98. button: true,
  99. child: Row(
  100. mainAxisAlignment: MainAxisAlignment.center,
  101. children: [
  102. Text(
  103. year.toString(),
  104. style: textStyle,
  105. ),
  106. if (isCurrentYear == true)
  107. Container(
  108. padding: const EdgeInsets.all(5),
  109. margin: const EdgeInsets.only(left: 5),
  110. decoration: const BoxDecoration(
  111. shape: BoxShape.circle,
  112. color: Colors.redAccent,
  113. ),
  114. ),
  115. ],
  116. ),
  117. ),
  118. ),
  119. ),
  120. );
  121. },
  122. );
  123. final selectDate=await showCalendarDatePicker2Dialog(
  124. context: context,
  125. config: config,
  126. dialogSize: const Size(325, 400)
  127. );
  128. if (selectDate != null) {
  129. var values=selectDate.map((e) => e!=null?e:null).toList();
  130. values.forEach((element) {
  131. print("values:${element}");
  132. });
  133. state.StartdateController.text=values[0].toString().replaceAll('00:00:00.000', '');
  134. if(values.length>1){
  135. state.EnddateController.text=values[1].toString().replaceAll('00:00:00.000', '');
  136. }
  137. else{
  138. state.EnddateController.text=values[0].toString().replaceAll('00:00:00.000', '');
  139. }
  140. update();
  141. }

 单模式
  1. List<DateTime?> _singleDatePickerValueWithDefaultValue = [DateTime.now(),];
  2. //单模式
  3. Widget _buildDefaultSingleDatePickerWithValue() {
  4. final config = CalendarDatePicker2Config(
  5. selectedDayHighlightColor: Colors.amber[900],
  6. weekdayLabels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  7. weekdayLabelTextStyle: const TextStyle(
  8. color: Colors.black87,
  9. fontWeight: FontWeight.bold,
  10. ),
  11. firstDayOfWeek: 1,
  12. controlsHeight: 50,
  13. controlsTextStyle: const TextStyle(
  14. color: Colors.black,
  15. fontSize: 15,
  16. fontWeight: FontWeight.bold,
  17. ),
  18. dayTextStyle: const TextStyle(
  19. color: Colors.amber,
  20. fontWeight: FontWeight.bold,
  21. ),
  22. disabledDayTextStyle: const TextStyle(
  23. color: Colors.grey,
  24. ),
  25. selectableDayPredicate: (day) => !day.difference(DateTime.now().subtract(const Duration(days: 3))).isNegative,
  26. );
  27. return Column(
  28. mainAxisSize: MainAxisSize.min,
  29. children: [
  30. const SizedBox(height: 10),
  31. const Text('Single Date Picker (With default value)'),
  32. CalendarDatePicker2(
  33. config: config,
  34. value: _singleDatePickerValueWithDefaultValue,
  35. onValueChanged: (dates) =>
  36. setState(() => _singleDatePickerValueWithDefaultValue = dates),
  37. ),
  38. const SizedBox(height: 10),
  39. Row(
  40. mainAxisSize: MainAxisSize.min,
  41. children: [
  42. const Text('Selection(s): '),
  43. const SizedBox(width: 10),
  44. Text(
  45. _getValueText(
  46. config.calendarType,
  47. _singleDatePickerValueWithDefaultValue,
  48. ),
  49. ),
  50. ],
  51. ),
  52. const SizedBox(height: 25),
  53. ],
  54. );
  55. }

                      

 

多模式
  1. List<DateTime?> _multiDatePickerValueWithDefaultValue = [
  2. DateTime(today.year, today.month, 1),
  3. DateTime(today.year, today.month, 5),
  4. DateTime(today.year, today.month, 14),
  5. DateTime(today.year, today.month, 17),
  6. DateTime(today.year, today.month, 25),
  7. ];
  8. //多模式
  9. Widget _buildDefaultMultiDatePickerWithValue() {
  10. final config = CalendarDatePicker2Config(
  11. calendarType: CalendarDatePicker2Type.multi,
  12. selectedDayHighlightColor: Colors.indigo,
  13. );
  14. return Column(
  15. mainAxisSize: MainAxisSize.min,
  16. children: [
  17. const SizedBox(height: 10),
  18. const Text('Multi Date Picker (With default value)'),
  19. CalendarDatePicker2(
  20. config: config,
  21. value: _multiDatePickerValueWithDefaultValue,
  22. onValueChanged: (dates) =>
  23. setState(() => _multiDatePickerValueWithDefaultValue = dates),
  24. ),
  25. const SizedBox(height: 10),
  26. Wrap(
  27. children: [
  28. const Text('Selection(s): '),
  29. const SizedBox(width: 10),
  30. Text(
  31. _getValueText(
  32. config.calendarType,
  33. _multiDatePickerValueWithDefaultValue,
  34. ),
  35. overflow: TextOverflow.ellipsis,
  36. maxLines: 1,
  37. softWrap: false,
  38. ),
  39. ],
  40. ),
  41. const SizedBox(height: 25),
  42. ],
  43. );
  44. }

                         

 

范围模式
  1. List<DateTime?> _rangeDatePickerValueWithDefaultValue = [
  2. DateTime(1999, 5, 6),
  3. DateTime(1999, 5, 21),
  4. ];
  5. //范围模式
  6. Widget _buildDefaultRangeDatePickerWithValue() {
  7. final config = CalendarDatePicker2Config(
  8. calendarType: CalendarDatePicker2Type.range,
  9. selectedDayHighlightColor: Colors.teal[800],
  10. weekdayLabelTextStyle: const TextStyle(
  11. color: Colors.black87,
  12. fontWeight: FontWeight.bold,
  13. ),
  14. controlsTextStyle: const TextStyle(
  15. color: Colors.black,
  16. fontSize: 15,
  17. fontWeight: FontWeight.bold,
  18. ),
  19. );
  20. return Column(
  21. mainAxisSize: MainAxisSize.min,
  22. children: [
  23. const SizedBox(height: 10),
  24. const Text('Range Date Picker (With default value)'),
  25. CalendarDatePicker2(
  26. config: config,
  27. value: _rangeDatePickerValueWithDefaultValue,
  28. onValueChanged: (dates) =>
  29. setState(() => _rangeDatePickerValueWithDefaultValue = dates),
  30. ),
  31. const SizedBox(height: 10),
  32. Row(
  33. mainAxisSize: MainAxisSize.min,
  34. children: [
  35. const Text('Selection(s): '),
  36. const SizedBox(width: 10),
  37. Text(
  38. _getValueText(
  39. config.calendarType,
  40. _rangeDatePickerValueWithDefaultValue,
  41. ),
  42. ),
  43. ],
  44. ),
  45. const SizedBox(height: 25),
  46. ],
  47. );
  48. }

                      

 

按钮确认调用CalendarDatePicker2WithActionButtons,仅当用户点击“确定”按钮时,此小部件才会发出更新的值
  1. List<DateTime?> _rangeDatePickerWithActionButtonsWithValue = [
  2. DateTime.now(),
  3. DateTime.now().add(const Duration(days: 5)),
  4. ];
  5. //按钮确定
  6. Widget _buildCalendarWithActionButtons() {
  7. final config = CalendarDatePicker2WithActionButtonsConfig(
  8. calendarType: CalendarDatePicker2Type.range,
  9. disableModePicker: true,
  10. );
  11. return Column(
  12. mainAxisSize: MainAxisSize.min,
  13. children: [
  14. const SizedBox(height: 10),
  15. const Text('Date Picker With Action Buttons'),
  16. CalendarDatePicker2WithActionButtons(
  17. config: config,
  18. value: _rangeDatePickerWithActionButtonsWithValue,
  19. onValueChanged: (dates) => setState(
  20. () => _rangeDatePickerWithActionButtonsWithValue = dates),
  21. ),
  22. const SizedBox(height: 10),
  23. Row(
  24. mainAxisSize: MainAxisSize.min,
  25. children: [
  26. const Text('Selection(s): '),
  27. const SizedBox(width: 10),
  28. Flexible(
  29. child: Text(
  30. _getValueText(
  31. config.calendarType,
  32. _rangeDatePickerWithActionButtonsWithValue,
  33. ),
  34. ),
  35. ),
  36. ],
  37. ),
  38. const SizedBox(height: 25),
  39. ],
  40. );
  41. }

                     

原文:https://pub.dev/packages/calendar_date_picker2 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/273775
推荐阅读
  

闽ICP备14008679号