Flutter Local Notification无法设置次日通知问题求助
Flutter Local Notifications 自定义日期通知触发异常解决办法
问题根源出在matchDateTimeComponents: DateTimeComponents.time这个参数上——它的作用是让通知每天在指定时间重复触发。如果当前时间早于15:17,调用方法的当天就会先触发一次,之后每天同一时间再重复触发,这就是你设置次日通知却当天触发的原因。
解决方案
1. 单次触发指定日期通知
如果只需要在次日15:17触发一次通知,直接移除matchDateTimeComponents参数(或设置为null),因为zonedSchedule默认就是单次触发逻辑。
同时注意:直接用now.day +1计算次日存在边界问题(比如当月最后一天会导致日期无效),建议用DateTime.add()方法安全计算次日,自动处理月份、年份的进位。
修正后的代码:
await flutterLocalNotificationsPlugin.zonedSchedule( task.id!.toInt(), task.title, task.note, // 安全计算次日15:17,自动处理月末、年末的日期进位 tz.TZDateTime.from(now.add(const Duration(days: 1)), tz.local).copyWith(hour: 15, minute: 17), const NotificationDetails( android: AndroidNotificationDetails( 'your channel id 3', 'your channel name', channelDescription: 'your channel description', priority: Priority.max, importance: Importance.max, sound: RawResourceAndroidNotificationSound('notification_sound'), ), iOS: DarwinNotificationDetails(sound: 'notification_sound.wav'), ), androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, // 移除重复触发的参数 payload: "${task.title}|${task.note}|${task.date}|", );
2. 重复触发通知(如果需要)
如果确实需要每天15:17重复触发通知,保留matchDateTimeComponents: DateTimeComponents.time即可,但此时通知会从当天开始触发,符合重复逻辑。
内容的提问来源于stack exchange,提问作者Esraa Hamada
相关产品推荐
相关产品推荐

