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

Flutter Local Notification中periodicallyShow与zonedSchedule结合方案咨询

Flutter Local Notification 每日特定时间重复通知实现

要实现每日指定时间(如10:00)重复触发通知,无需混用periodicallyShow和zonedSchedule,zonedSchedule本身就能精准适配时区并实现每日固定时间重复的需求。以下是完整实现代码:

1. 初始化通知插件

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> initNotifications() async {
  // 初始化时区数据
  tz.initializeTimeZones();
  // 设置本地时区(示例为上海时区,可根据设备自动适配)
  tz.setLocalLocation(tz.getLocation('Asia/Shanghai'));

  const AndroidInitializationSettings androidInitSettings =
      AndroidInitializationSettings('@mipmap/ic_launcher');
  const InitializationSettings initSettings =
      InitializationSettings(android: androidInitSettings);
  await flutterLocalNotificationsPlugin.initialize(initSettings);
}

2. 调度每日10:00重复通知

Future<void> scheduleDailyTenAMNotification() async {
  final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
  // 构建当日10:00的时间对象
  tz.TZDateTime scheduledDate = tz.TZDateTime(
    tz.local,
    now.year,
    now.month,
    now.day,
    10,
    0,
    0,
  );

  // 如果当前时间已过10点,自动顺延至次日10点
  if (scheduledDate.isBefore(now)) {
    scheduledDate = scheduledDate.add(const Duration(days: 1));
  }

  await flutterLocalNotificationsPlugin.zonedSchedule(
    0, // 唯一通知ID
    '每日定时提醒',
    '现在是10:00,执行预设任务!',
    scheduledDate,
    const NotificationDetails(
      android: AndroidNotificationDetails(
        'daily_reminder_channel', // 渠道ID(Android 8.0+必填)
        '每日提醒', // 渠道名称
        channelDescription: '每日固定时间触发的提醒通知',
        importance: Importance.max,
        priority: Priority.high,
      ),
    ),
    androidAllowWhileIdle: true, // 允许设备休眠时触发通知
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime,
    matchDateTimeComponents: DateTimeComponents.time, // 核心:按每日同一时间重复
  );
}

关键说明

  • matchDateTimeComponents: DateTimeComponents.time是实现每日重复的核心配置,它会让通知在每天的指定时间自动触发,无需额外调用periodicallyShow。
  • 时区初始化必须完成,否则会出现跨时区的时间偏差问题。
  • 如果需要修改通知时间或取消通知,可调用flutterLocalNotificationsPlugin.cancel(通知ID)清除原有任务后重新调度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:20:13