Created
March 13, 2024 22:59
-
-
Save gdelataillade/3dae217917d417c5f367557489133619 to your computer and use it in GitHub Desktop.
Example of implementation of periodic alarms with Flutter alarm plugin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's say we want to set a periodic alarm for each Monday, Wednesday and Friday at 9:41. | |
// Run this function on app launch when Alarm.init is done. | |
// It will make sure your periodic alarms are set for the following week. | |
Future<void> periodicAlarms() async { | |
const nbDays = 7; // Number of following days to potentially set alarm | |
const time = TimeOfDay(hour: 9, minute: 41); // Time of the periodic alarm | |
const days = [ | |
DateTime.monday, | |
DateTime.wednesday, | |
DateTime.friday, | |
]; // Days of the week to set the alarm | |
final now = DateTime.now(); | |
// Loop through the next days | |
for (var i = 0; i < nbDays; i++) { | |
final dateTime = DateTime( | |
now.year, | |
now.month, | |
now.day, | |
time.hour, | |
time.minute, | |
).add(Duration(days: i)); | |
if (days.contains(dateTime.weekday)) { | |
final alarmSettings = AlarmSettings( | |
id: dateTime.day, | |
dateTime: dateTime, | |
assetAudioPath: 'assets/your_audio.mp3', | |
notificationTitle: 'Alarm ringing !', | |
notificationBody: 'Periodic alarm ringing, day ${dateTime.day}.', | |
); | |
await Alarm.set( | |
alarmSettings: alarmSettings, | |
); // If the alarm was already set, it will just override it | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment