Flutter之日期选择器 calendar_date_picker2

这篇具有很好参考价值的文章主要介绍了Flutter之日期选择器 calendar_date_picker2。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

calendar_date_picker2主要由两个小部件组成:

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

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

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

Calendar UI related configurations

(日历UI的相关配置)

value List<DateTime?>

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

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

onValueChanged ValueChanged<List<DateTime?>>?

Called when the selected dates changed

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

displayedMonthDate DateTime?

Date to control calendar displayed month

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

onDisplayedMonthChanged ValueChanged<DateTime>?

The initially displayed view of the calendar picker

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

 CalendarDatePicker2Config的参数
Option Type Description
calendarType CalendarDatePicker2Type?

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

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

firstDate DateTime?

The earliest allowable DateTime user can select

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

lastDate DateTime?

The latest allowable DateTime user can select

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

currentDate DateTime?

The DateTime representing today which will be outlined in calendar

(用户当前选择的时间)

calendarViewMode DatePickerMode?

The initially displayed view of the calendar picker

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

weekdayLabels List<String>?

Custom weekday labels, should starts with Sunday

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

weekdayLabelTextStyle TextStyle?

Custom text style for weekday labels

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

firstDayOfWeek int?

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

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

controlsHeight double?

Custom height for calendar control toggle's height

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

lastMonthIcon Widget?

Custom icon for last month button control

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

nextMonthIcon Widget?

Custom icon for next month button control

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

controlsTextStyle TextStyle?

Custom text style for calendar mode toggle control

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

dayTextStyle TextStyle?

Custom text style for calendar day text

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

selectedDayTextStyle TextStyle?

Custom text style for selected calendar day text

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

selectedRangeDayTextStyle TextStyle?

Custom text style for selected range calendar day(s)

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

selectedDayHighlightColor Color?

The highlight color selected day

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

selectedRangeHighlightColor Color?

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

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

disabledDayTextStyle TextStyle?

Custom text style for disabled calendar day(s)

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

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

Custom text style for years list

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

selectedYearTextStyle TextStyle?

Custom text style for selected year

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

dayBorderRadius BorderRadius?

Custom border radius for day indicator

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

yearBorderRadius BorderRadius?

Custom border radius for year indicator

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

selectableDayPredicate SelectableDayPredicate?

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

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

dayTextStylePredicate CalendarDayTextStylePredicate?

Function to provide full control over calendar days text style

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

dayBuilder CalendarDayBuilder? Function to provide full control over day widget UI
(构造日选择部件UI)
yearBuilder CalendarYearBuilder?

Function to provide full control over year widget UI

(构造年份选择部件UI)

disableModePicker bool?

Flag to disable mode picker and hide the toggle icon

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

centerAlignModePicker bool?

Flag to centralize year and month text label in controls

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

customModePickerIcon Widget? Custom icon for the mode picker button icon
(模式选择器按钮图标的自定义图标)
modePickerTextHandler CalendarModePickerTextHandler?

Function to control mode picker displayed text

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

 CalendarDatePicker2WithActionButtonsConfig 除上面的配置外还有其余9个额外的选项
Option Type Description
gapBetweenCalendarAndButtons double?

The gap between calendar and action buttons

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

cancelButtonTextStyle TextStyle?

Text style for cancel button

(取消按钮的文本样式)

cancelButton Widget?

Custom cancel button

(自定义取消按钮)

okButtonTextStyle TextStyle?

Text style for ok button

(确定按钮的文本样式)

okButton Widget?

Custom ok button

(自定义确定按钮)

openedFromDialog bool?

Is the calendar opened from dialog

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

closeDialogOnCancelTapped bool?

Close dialog after user taps the CANCEL button

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

closeDialogOnOkTapped bool?

Close dialog after user taps the OK button

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

buttonPadding EdgeInsets?

Custom wrapping padding for Ok & Cancel buttons

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

使用步骤:

1、 添加依赖

dependencies:
  calendar_date_picker2: ^0.5.2
写在前面的_getValueText,用于修改日期格式
 String _getValueText(CalendarDatePicker2Type datePickerType, List<DateTime?> values,) {

    values = values.map((e) => e != null ? DateUtils.dateOnly(e) : null).toList();
    var valueText = (values.isNotEmpty ? values[0] : null).toString().replaceAll('00:00:00.000', '');

    if (datePickerType == CalendarDatePicker2Type.multi) {
      valueText = values.isNotEmpty ? values.map((v) => v.toString().replaceAll('00:00:00.000', '')).join(', ') : 'null';
    }

    else if (datePickerType == CalendarDatePicker2Type.range) {
      if (values.isNotEmpty) {
        final startDate = values[0].toString().replaceAll('00:00:00.000', '');
        final endDate = values.length > 1 ? values[1].toString().replaceAll('00:00:00.000', '') : 'null';
        valueText = '$startDate to $endDate';
      }
      else {
        return 'null';
      }
    }
    return valueText;
  }
对话框模式

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

 //工作日文本样式
    const dayTextStyle = TextStyle(color: Colors.black, fontWeight: FontWeight.w700);
    //周末文本样式
    final weekendTextStyle = TextStyle(color: Colors.grey[500], fontWeight: FontWeight.w600);
    //与当前日期相同的日期
    final anniversaryTextStyle = TextStyle(
      color: Colors.red[400],
      fontWeight: FontWeight.w700,
      decoration: TextDecoration.underline,
    );

    final config = CalendarDatePicker2WithActionButtonsConfig(
      //日文本样式
      dayTextStyle: dayTextStyle,
      //日期选择器类型——范围
      calendarType: CalendarDatePicker2Type.range,
      //所选日期的突出显示颜色
      selectedDayHighlightColor: Colors.purple[800],
      //用户点击取消按钮后关闭对话框
      closeDialogOnCancelTapped: true,
      //一周的第一天,0表示周日,6表示周六
      firstDayOfWeek: 1,
      //工作日标签的自定义文本样式
      weekdayLabelTextStyle: const TextStyle(
        color: Colors.black87,
        fontWeight: FontWeight.bold,
      ),
      //日历模式切换控件的自定义文本样式
      controlsTextStyle: const TextStyle(
        color: Colors.black,
        fontSize: 15,
        fontWeight: FontWeight.bold,
      ),

      //用于在控件中集中年份和月份文本标签的标志
      centerAlignModePicker: true,

      //模式选择器按钮图标的自定义图标
      customModePickerIcon: const SizedBox(),

      //选定日历日文本的自定义文本样式
      selectedDayTextStyle: dayTextStyle.copyWith(color: Colors.white),

      //提供对日历日文本样式的完全控制的功能
      dayTextStylePredicate: ({required date}) {
        TextStyle? textStyle;
        if (date.weekday == DateTime.saturday ||
            date.weekday == DateTime.sunday) {
          textStyle = weekendTextStyle;
        }
        /*if (DateUtils.isSameDay(date, DateTime(2021, 1, 25))) {
          textStyle = anniversaryTextStyle;
        }*/
        if (DateUtils.isSameDay(date, DateTime.now())) {
          textStyle = anniversaryTextStyle;
        }
        return textStyle;
      },

      //构造日部件UI
      dayBuilder: ({required date, textStyle, decoration, isSelected, isDisabled, isToday,}) {

        Widget? dayWidget;
        if (date.day % 3 == 0 && date.day % 9 != 0) {
          dayWidget = Container(
            decoration: decoration,
            child: Center(
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: [
                  Text(
                    MaterialLocalizations.of(context).formatDecimal(date.day),
                    style: textStyle,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 27.5),
                    child: Container(
                      height: 4,
                      width: 4,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        color: isSelected == true
                            ? Colors.white
                            : Colors.grey[500],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        }
        return dayWidget;
      },

      //构造年份选择部件
      yearBuilder: ({required year, decoration, isCurrentYear, isDisabled, isSelected, textStyle,}) {
        return Center(
          child: Container(
            decoration: decoration,
            height: 36,
            width: 72,
            child: Center(
              child: Semantics(
                selected: isSelected,
                button: true,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      year.toString(),
                      style: textStyle,
                    ),
                    if (isCurrentYear == true)
                      Container(
                        padding: const EdgeInsets.all(5),
                        margin: const EdgeInsets.only(left: 5),
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.redAccent,
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );

    final selectDate=await showCalendarDatePicker2Dialog(
      context: context,
      config: config,
      dialogSize: const Size(325, 400)
    );
    if (selectDate != null) {

      var values=selectDate.map((e) => e!=null?e:null).toList();
      values.forEach((element) {
        print("values:${element}");
      });
      state.StartdateController.text=values[0].toString().replaceAll('00:00:00.000', '');
      if(values.length>1){
        state.EnddateController.text=values[1].toString().replaceAll('00:00:00.000', '');
      }
      else{
        state.EnddateController.text=values[0].toString().replaceAll('00:00:00.000', '');
      }
    
    update();
  }

flutter 日期选择器,Flutter学习,flutter

 单模式
  List<DateTime?> _singleDatePickerValueWithDefaultValue = [DateTime.now(),];
  //单模式
  Widget _buildDefaultSingleDatePickerWithValue() {
    final config = CalendarDatePicker2Config(
      selectedDayHighlightColor: Colors.amber[900],
      weekdayLabels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      weekdayLabelTextStyle: const TextStyle(
        color: Colors.black87,
        fontWeight: FontWeight.bold,
      ),
      firstDayOfWeek: 1,
      controlsHeight: 50,
      controlsTextStyle: const TextStyle(
        color: Colors.black,
        fontSize: 15,
        fontWeight: FontWeight.bold,
      ),
      dayTextStyle: const TextStyle(
        color: Colors.amber,
        fontWeight: FontWeight.bold,
      ),
      disabledDayTextStyle: const TextStyle(
        color: Colors.grey,
      ),
      selectableDayPredicate: (day) => !day.difference(DateTime.now().subtract(const Duration(days: 3))).isNegative,
    );
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 10),
        const Text('Single Date Picker (With default value)'),
        CalendarDatePicker2(
          config: config,
          value: _singleDatePickerValueWithDefaultValue,
          onValueChanged: (dates) =>
              setState(() => _singleDatePickerValueWithDefaultValue = dates),
        ),
        const SizedBox(height: 10),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('Selection(s):  '),
            const SizedBox(width: 10),
            Text(
              _getValueText(
                config.calendarType,
                _singleDatePickerValueWithDefaultValue,
              ),
            ),
          ],
        ),
        const SizedBox(height: 25),
      ],
    );
  }

flutter 日期选择器,Flutter学习,flutter

                      

flutter 日期选择器,Flutter学习,flutter

 

多模式
List<DateTime?> _multiDatePickerValueWithDefaultValue = [
    DateTime(today.year, today.month, 1),
    DateTime(today.year, today.month, 5),
    DateTime(today.year, today.month, 14),
    DateTime(today.year, today.month, 17),
    DateTime(today.year, today.month, 25),
  ];
//多模式
  Widget _buildDefaultMultiDatePickerWithValue() {
    final config = CalendarDatePicker2Config(
      calendarType: CalendarDatePicker2Type.multi,
      selectedDayHighlightColor: Colors.indigo,
    );
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 10),
        const Text('Multi Date Picker (With default value)'),
        CalendarDatePicker2(
          config: config,
          value: _multiDatePickerValueWithDefaultValue,
          onValueChanged: (dates) =>
              setState(() => _multiDatePickerValueWithDefaultValue = dates),
        ),
        const SizedBox(height: 10),
        Wrap(
          children: [
            const Text('Selection(s):  '),
            const SizedBox(width: 10),
            Text(
              _getValueText(
                config.calendarType,
                _multiDatePickerValueWithDefaultValue,
              ),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              softWrap: false,
            ),
          ],
        ),
        const SizedBox(height: 25),
      ],
    );
  }

flutter 日期选择器,Flutter学习,flutter

                         

flutter 日期选择器,Flutter学习,flutter

 

范围模式
 List<DateTime?> _rangeDatePickerValueWithDefaultValue = [
    DateTime(1999, 5, 6),
    DateTime(1999, 5, 21),
  ];
//范围模式
  Widget _buildDefaultRangeDatePickerWithValue() {
    final config = CalendarDatePicker2Config(
      calendarType: CalendarDatePicker2Type.range,
      selectedDayHighlightColor: Colors.teal[800],
      weekdayLabelTextStyle: const TextStyle(
        color: Colors.black87,
        fontWeight: FontWeight.bold,
      ),
      controlsTextStyle: const TextStyle(
        color: Colors.black,
        fontSize: 15,
        fontWeight: FontWeight.bold,
      ),
    );
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 10),
        const Text('Range Date Picker (With default value)'),
        CalendarDatePicker2(
          config: config,
          value: _rangeDatePickerValueWithDefaultValue,
          onValueChanged: (dates) =>
              setState(() => _rangeDatePickerValueWithDefaultValue = dates),
        ),
        const SizedBox(height: 10),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('Selection(s):  '),
            const SizedBox(width: 10),
            Text(
              _getValueText(
                config.calendarType,
                _rangeDatePickerValueWithDefaultValue,
              ),
            ),
          ],
        ),
        const SizedBox(height: 25),
      ],
    );
  }

flutter 日期选择器,Flutter学习,flutter

                      

flutter 日期选择器,Flutter学习,flutter

 

按钮确认调用CalendarDatePicker2WithActionButtons,仅当用户点击“确定”按钮时,此小部件才会发出更新的值
List<DateTime?> _rangeDatePickerWithActionButtonsWithValue = [
    DateTime.now(),
    DateTime.now().add(const Duration(days: 5)),
  ];
 //按钮确定
  Widget _buildCalendarWithActionButtons() {
    final config = CalendarDatePicker2WithActionButtonsConfig(
      calendarType: CalendarDatePicker2Type.range,
      disableModePicker: true,
    );
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 10),
        const Text('Date Picker With Action Buttons'),
        CalendarDatePicker2WithActionButtons(
          config: config,
          value: _rangeDatePickerWithActionButtonsWithValue,
          onValueChanged: (dates) => setState(
                  () => _rangeDatePickerWithActionButtonsWithValue = dates),
        ),
        const SizedBox(height: 10),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('Selection(s):  '),
            const SizedBox(width: 10),
            Flexible(
              child: Text(
                _getValueText(
                  config.calendarType,
                  _rangeDatePickerWithActionButtonsWithValue,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 25),
      ],
    );
  }

                     

flutter 日期选择器,Flutter学习,flutter文章来源地址https://www.toymoban.com/news/detail-733767.html

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

到了这里,关于Flutter之日期选择器 calendar_date_picker2的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • element-ui 日期时间选择器el-date-picker 设置禁止选择日期

    使用日期选择器时,有的时候需要禁止选择一些日期,我们可以通过快捷选项 picker-options 对象中的禁用日期属性 disabledDate 来设置。

    2024年02月11日
    浏览(41)
  • 【VUE】el-date-picker日期选择器回显

    使用elementUI - el-date-picker 日期选择器 在请求到后端接口后,返回的数据中,日期数据回显到页面的el-date-picker组件中 1.  Vue.set( target, propertyName/index, value )      数组:第一个参数是要修改的数组, 第二个值是修改的下标或字段,第三个是要修改成什么值。     2. this.$set(this

    2024年02月11日
    浏览(51)
  • el-date-picker日期选择器奇怪的问题解决

    问题描述 :点击日期选择器,出现日历下拉框,选择了日期后绑定的value值不变;绑定 @change 事件,监听不到 解决方案 :添加input事件,$forceUpdate()

    2024年02月07日
    浏览(31)
  • element UI中的el-date-picker日期选择的日期偏差问题记录

    el-date-picker日期选择的的日期和输出的日期不相同 错误的代码 没问题的代码 注: yyyy-MM-dd 和 yyyy-MM-DD 大小写一定要注意,忘记了 一定要看清楚文档!!!

    2024年04月11日
    浏览(34)
  • el-date-picker实现通过其他方式触发日期选择器

    el-date-picker 目前只能通过点击input输入框触发日期选择器,项目中需要通过其他方式触发日期选择器同时把input输入框去掉,如点击另一个按钮事件 来触发日期选择器框展开。 该模块由于后端接口数据传输限制 在前面文章里做了些许改动。 需求左右切换 可以快速找到年份,

    2023年04月08日
    浏览(29)
  • element ui el-date-picker 禁止选择指定日期

    1)禁止选择当天之前的日期 禁止选择包含当天及其之前的日期 2)禁用选择当天之后的日期 禁止选择包含当天及其之后的日期 3)禁止选择自定义加载的日期,比如打开编辑框,禁止选择当前数据回显日期之前的日期 禁止选择之后  禁止选择之前   - 8.64e7 表示可选择当天时

    2024年02月11日
    浏览(165)
  • 【Element UI】日期选择器el-date-picker 默认选中当前日期==> 不可选当日之前的日期

    一个人能否合理表达自己的攻击性是健康与否的重要标准。 参考Element UI  Element - The world\\\'s most popular Vue UI framework  目录 1.默认当前天+之前日期不可选 2.默认当前天+之后日期不可选  

    2024年02月13日
    浏览(42)
  • Element-UI日期选择器el-date-picker给指定日期添加红点标注

            今天在项目开发中有一个需求,要求日期选择器中,指定的日期显示标注,标识该日期有待处理的内容。         查阅资料后我们得知,ElementUI在2.12.0版本里,日期选择器的picker-options新增了cellClassName方法,那么我们就来看一下如何实现。 1、badgeDate为存在待

    2024年02月11日
    浏览(44)
  • ElementUI中的el-date-picker日期选择器的格式转换问题

    使用el-date-picker日期选择器选择的日期是string类型且是箭头所指的这种格式 1、在这个组件后面加上这两个,可以修改格式 2、在后端实体类上加上注解 即使前端的是string类型,但是通过json自带的格式匹配注解工具,将string转换成LocalDateTime类型 用npm下载一个moment.js 1、 2、在

    2024年02月12日
    浏览(34)
  • 接着element ui 日期选择器el-date-picker 修改指定日期背景 点击指定背景色日期变深色

    然后点击浅绿色变深绿色 点击浅红色变深红色 默认不变 还是选中蓝色 最好隔离一下不要影响到其他日期选择器的样式

    2024年02月03日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包