毎日午前 10 時にローカル通知したいの?|Example|FlutterLocalNotifications|Android|Flutter


FlutterLocalNotifications 13.0.0 を使って、毎日、午前 10:00 にローカル通知が発生するようにスケジュールする方法は、公式の Example で以下の通りに掲載されているよ。

---
Future<void> _scheduleDailyTenAMNotification() async {
  await flutterLocalNotificationsPlugin.zonedSchedule(
      0,
      'daily scheduled notification title',
      'daily scheduled notification body',
      _nextInstanceOfTenAM(),
      const NotificationDetails(
        android: AndroidNotificationDetails(
            'daily notification channel id',
            'daily notification channel name',
            channelDescription: 'daily notification description'),
      ),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time);
}
---

通知時間を生成している「_nextInstanceOfTenAM()」はどうなっているのかというと、以下のように、今日の日時を取得して、時間を 10 時に設定している。その時間を既に現在時刻が過ぎてしまっていたら、1 日をプラスして明日(24 時間後)の 10 時に設定している。

---
tz.TZDateTime _nextInstanceOfTenAM() {
  final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
  tz.TZDateTime scheduledDate =
      tz.TZDateTime(tz.local, now.year, now.month, now.day, 10);
  if (scheduledDate.isBefore(now)) {
    scheduledDate = scheduledDate.add(const Duration(days: 1));
  }
  return scheduledDate;
}
---

matchDateTimeComponents」は公式の説明があって、以下の通り、どういった単位でローカル通知を組み合わせるか、という設定。

There is an optional matchDateTimeComponents parameter that can be used to schedule a notification to appear on a daily or weekly basis by telling the plugin to match on the time or a combination of day of the week and time respectively.

「DateTimeComponents.time」は”時間”単位を指定しているので、これを設定すると毎日、同じ時間にローカル通知がされるということだ。


関連する記事


直近に読んでいた漫画(おすすめ)

コメント

このブログの人気の投稿

ImagePicker を操作すると「Lost connection to device.」とだけ言い残して強制終了するの?|iOS|Flutter

Android SDK バージョン(コンパイルに使用する Android API レベル)を変更するの?|compileSdkVersion|SDK|Android|Flutter