I had a similar condition for my app, where I had to trigger an event at a certain time in a day.
We cannot use Timer function, because once the app is closed, the OS kills the app and the timer also stops running.
So we need to save our time somewhere, and then check it, if that saved time has come now.
For that first I created a DateTime instance and saved it on Firestore. You can save that DateTime instance on local Database also, eg:SQFlite etc.
//DateTime instance with a specific date and time-
DateTime atFiveInEvening;
//this should be a correctly formatted string, which complies with a subset of ISO 8601
atFiveInEvening= DateTime.parse("2021-08-02 17:00:00Z");
//Or a time after 3 hours from now
DateTime threehoursFromNow;
threeHoursFromNow = DateTime.now().add(Duration(hours: 3));
Now save this instance to FireStore with an ID-
saveTimeToFireStore() async {
await FirebaseFirestore.instance.collection('users').doc('Z0ZuoW8npwuvmBzmF0Wt').set({
'atFiveInEvening':atFiveInEvening,
});
}
Now retrieve this set time from Firestore when the app opens-
getTheTimeToTriggerEvent() async {
final DocumentSnapshot doc =
await FirebaseFirestore.instance.collection('users').doc('Z0ZuoW8npwuvmBzmF0Wt').get();
timeToTriggerEvent= doc['atFiveInEvening'].toDate();
//Now use If/Else statement to know, if the current time is same as/or after the
//time set for trigger, then trigger the event,
if(DateTime.now().isAfter(timeToTriggerEvent)) {
//Trigger the event which you want to trigger.
}
}
But here we'll have to run the function getTheTimeToTriggerEvent() again and again to check if the time has come.