如何设置Flutter本地通知从明天开始每日重复?
问题解决思路与修正代码
核心问题分析
你遇到的今日触发通知的问题,大概率是因为以下两点:
- 旧通知未清理:同ID的历史通知未取消,导致重复触发
- 调度逻辑的细微漏洞:虽然构造了明天的时间,但时区处理或重复规则的配合可能导致插件误判触发时机
修正方案
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
相关产品推荐
相关产品推荐

