如何检查Flutter会议提前30分钟的通知是否已调度?
解决重复调度通知的问题
要避免每次打开应用时重复调度同一会议的通知,核心是检查该通知是否已处于待处理状态,同时要为每个会议分配唯一的通知ID,避免不同会议的通知互相覆盖。
步骤1:修改调度方法,添加唯一ID与检查逻辑
首先,为每个会议的通知分配一个唯一的notificationId(比如用会议ID或时间组合生成),然后在调度前调用pendingNotificationRequests()获取所有待处理通知,判断是否已存在对应ID的通知:
Future<void> scheduleNotifications( int notificationId, String title, String payload, int yy, int mm, int dd, int hh, int ii, ) async { final tz.Location timeZoneName = tz.getLocation('Africa/Cairo'); tz.setLocalLocation(timeZoneName); DateTime currentTime = tz.TZDateTime.now(timeZoneName); var schedule30Before = tz.TZDateTime(timeZoneName, yy, mm, dd, hh, ii).subtract(const Duration(minutes: 30)); if (currentTime.isBefore(schedule30Before)) { // 获取所有待处理的通知请求 List<PendingNotificationRequest> pendingNotifications = await flutterLocalNotificationsPlugin.pendingNotificationRequests(); // 检查当前ID的通知是否已调度 bool isNotificationScheduled = pendingNotifications.any((request) => request.id == notificationId); if (!isNotificationScheduled) { await flutterLocalNotificationsPlugin.zonedSchedule( notificationId, title, "The Webinar will start after 30 minutes", schedule30Before, NotificationDetails(android: _androidNotificationDetails), androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, payload: payload, ); } } }
步骤2:生成唯一通知ID
调用方法时,需要为每个会议生成唯一的notificationId,比如用会议的时间组合生成(确保每个会议时间对应唯一ID):
// 示例:用会议时间生成唯一ID int notificationId = yy * 1000000 + mm * 10000 + dd * 100 + hh * 60 + ii; // 调用调度方法 await scheduleNotifications(notificationId, "会议提醒", "会议ID:123", 2024, 10, 5, 14, 30);
关键说明
pendingNotificationRequests()仅返回未触发的待处理通知,如果通知已经触发(比如会议已经开始过),则不会出现在列表中,此时即使打开应用也不会重复调度。- 必须使用唯一ID:如果所有通知都用同一个ID(比如原来的0),后续调度会覆盖之前的通知,同时无法区分不同会议的通知是否已调度。
内容的提问来源于stack exchange,提问作者Mohamed Amin
相关产品推荐
相关产品推荐

