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


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

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

通知時間を生成している「_nextInstanceOfMondayTenAM()」はどうなっているのかというと、以下のように、「_nextInstanceOfTenAM()」で 10 時に設定し(後述)、曜日が月曜日でなければ、月曜日になるまで日付を while 文で進めて設定している。

---
tz.TZDateTime _nextInstanceOfMondayTenAM() {
  tz.TZDateTime scheduledDate = _nextInstanceOfTenAM();
  while (scheduledDate.weekday != DateTime.monday) {
    scheduledDate = scheduledDate.add(const Duration(days: 1));
  }
  return scheduledDate;
}
---

さて「_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.dayOfMonthAndTime」は”日付と時間”単位を指定しているので、これを設定すると毎月、同じ日付と時間にローカル通知がされるということだ。


関連する記事


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

コメント

このブログの人気の投稿

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

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