You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用add_2_calendar包为DateTime添加时间时出错

问题解决:Flutter add_2_calendar 包中 Duration 常量表达式错误

核心错误原因

你在创建Duration时加了const关键字,但传入的参数是运行时动态计算的值(比如int.parse(event.eventDuration!)、event.recurrenceEndDate相关计算),而const要求参数必须是编译期就能确定的常量,这直接触发了const_eval_throws_exception错误。

具体修正步骤

  1. 移除Duration前的const:所有带动态参数的Duration不能用const修饰
  2. 修复无效的日期差计算:你当前代码里int eventRecurrenceEndDate = event.eventDate!.difference(event.eventDate!).inDays;是同一个日期相减,结果恒为0,完全无意义,需要替换为实际结束日期与起始日期的差
  3. 修正变量引用错误:recurrence部分你写了event.recurrenceEndDate,但前面定义的变量是eventRecurrenceEndDate,需要统一变量名

修正后的完整代码

class AddEventsToAllCalendars {
  void addEvent(Events event) {
    Add2Calendar.addEvent2Cal(buildEvent(event));
  }

  Event buildEvent(Events event) {
    // 修正:计算实际的 recurrence 结束天数(假设你的Events类有recurrenceEndDate字段)
    final int recurrenceDays = event.recurrenceEndDate!.difference(event.eventDate!).inDays;

    Frequency freq = Frequency.daily;
    if (event.frequency == 'daily') {
      freq = Frequency.daily;
    } else if (event.frequency == 'weekly') {
      freq = Frequency.weekly;
    } else if (event.frequency == 'monthly') {
      freq = Frequency.monthly;
    } else {
      freq = Frequency.yearly;
    }

    return Event(
      title: event.eventName!,
      description: event.eventDescription,
      location: event.location,
      startDate: event.eventStartTime!,
      // 移除const,用动态解析的分钟数
      endDate: event.eventStartTime!.add(Duration(minutes: int.parse(event.eventDuration!))),
      allDay: event.allDay,
      androidParams: const AndroidParams(
        emailInvites: ["test@gmail.com"],
      ),
      recurrence: Recurrence(
        frequency: freq,
        // 移除const,用计算好的天数
        endDate: event.eventStartTime!.add(Duration(days: recurrenceDays)),
      ),
    );
  }
}

额外注意点

  • 确保Events类中的recurrenceEndDate、eventDuration等字段不为空,否则!可能触发空指针异常,建议结合null安全处理(比如用??设置默认值)
  • 如果eventDuration本身是整数类型,不需要int.parse,直接使用即可

内容的提问来源于stack exchange,提问作者LostTexan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:17:05