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

Flutter Awesome Notifications是否支持结束日期功能?如何实现到期停发通知?

解决重复通知在指定日期停止触发的问题

把endDate放在payload里无法实现停止通知的需求,因为payload只是通知触发时携带的附加数据,不会影响系统对重复通知的调度逻辑。重复通知一旦创建,会按设定周期持续触发,直到主动调用取消方法。以下是可行的实现方案:

步骤1:存储通知ID与对应结束日期

需要把每个重复通知的ID和结束日期保存在本地(比如用shared_preferences),方便后续检查过期状态:

// 创建通知后,存储ID和结束日期
final prefs = await SharedPreferences.getInstance();
await prefs.setString('notification_$id', endDate.toString());

步骤2:通知触发时检查并取消过期通知

通过监听通知的接收事件,每次通知触发时判断当前时间是否超过结束日期,若过期则取消该通知:

// 监听通知接收事件
AwesomeNotifications().actionStream.listen((receivedNotification) async {
  final notificationId = receivedNotification.id;
  final prefs = await SharedPreferences.getInstance();
  final endDateStr = prefs.getString('notification_$notificationId');
  
  if (endDateStr != null) {
    final endDate = DateTime.parse(endDateStr);
    final now = DateTime.now();
    
    // 若当前时间已超过结束日期,取消重复通知并删除本地记录
    if (now.isAfter(endDate)) {
      await AwesomeNotifications().cancel(notificationId);
      await prefs.remove('notification_$notificationId');
    }
  }
});

步骤3:应用启动时检查过期通知

如果应用处于后台或未运行,通知触发时的监听可能不生效,因此在应用启动时主动检查所有存储的通知,取消已过期的:

// 检查并取消过期通知的方法
Future<void> checkExpiredNotifications() async {
  final prefs = await SharedPreferences.getInstance();
  // 筛选所有存储的通知记录
  final notificationKeys = prefs.getKeys().where((key) => key.startsWith('notification_'));
  
  for (final key in notificationKeys) {
    final notificationId = int.parse(key.split('_').last);
    final endDateStr = prefs.getString(key);
    
    if (endDateStr != null) {
      final endDate = DateTime.parse(endDateStr);
      if (DateTime.now().isAfter(endDate)) {
        await AwesomeNotifications().cancel(notificationId);
        await prefs.remove(key);
      }
    }
  }
}

// 在页面初始化或main函数中调用
@override
void initState() {
  super.initState();
  checkExpiredNotifications();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:48:36