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

如何设置Flutter本地通知从明天开始每日重复?

问题解决思路与修正代码

核心问题分析

你遇到的今日触发通知的问题,大概率是因为以下两点:

  1. 旧通知未清理:同ID的历史通知未取消,导致重复触发
  2. 调度逻辑的细微漏洞:虽然构造了明天的时间,但时区处理或重复规则的配合可能导致插件误判触发时机

修正方案

1. 先清理旧通知,再调度新通知

在调度新通知前,先取消同ID的历史通知,避免冲突:

static Future<void> scheduleNotification({
  required int id,
  required String title,
  required String body,
  required tz.TZDateTime tzDateTime,
  bool repeatDaily = false,
}) async {
  // 关键:先取消同ID的旧通知
  await _flutterLocalNotificationsPlugin.cancel(id);
  
  await _flutterLocalNotificationsPlugin.zonedSchedule(
    id,
    title,
    body,
    tzDateTime,
    NotificationDetails(android: _androidNotificationDetails),
    matchDateTimeComponents: repeatDaily
        ? DateTimeComponents.time
        : DateTimeComponents.dateAndTime,
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime,
    // 如需精确触发,改为exactAllowWhileIdle(耗电略增),否则保持inexact
    androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
  );
}

2. 可靠构造明日指定时间的TZDateTime

避免用add(Duration(days:1))的间接方式,直接构造明日日期更稳妥:

// 获取当前本地时区时间
final now = tz.TZDateTime.now(tz.local);
// 构造明日的日期实例
final tomorrow = now.add(const Duration(days: 1));
// 生成明日指定时分的调度时间
final scheduledTime = tz.TZDateTime(
  tz.local,
  tomorrow.year,
  tomorrow.month,
  tomorrow.day,
  assignmentReminderTime.hour,
  assignmentReminderTime.minute,
);

// 调用调度方法
scheduleNotification(
  id: assignmentReminder.id,
  title: assignmentReminder.title,
  body: assignmentReminder.body,
  tzDateTime: scheduledTime,
  repeatDaily: true,
);

额外检查点

  • 确认assignmentReminderTime的时分设置正确,没有误写成今日已过的时间(即使是,明日的该时间也属于未来,不会今日触发)
  • 确保timezone包已正确初始化(flutter_local_notifications依赖时区配置)
  • iOS需在Info.plist中配置通知权限相关字段,Android需在Manifest中声明通知权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:23:14