I want to send a scheduled push notification using firebase messaging from my flutter app.
I use the below code to send a push notification from my app, which works without any issues:
Future<bool> callOnFcmApiSendPushNotifications(String title, String body, List<dynamic> receivers, {String? image = "", String screen = ''}) async {
print('normal message');
List<dynamic> tokens = await pushNotificationsManager.getTokens(receivers);
final postUrl = 'https://fcm.googleapis.com/fcm/send';
Map<String, dynamic> data;
data = {
"registration_ids" : tokens,
"collapse_key" : "type_a",
"notification" : {
"title": title,
"body" : body,
"sound": "default",
"click_action": "FLUTTER_NOTIFICATION_CLICK",
},
'data':{
"title": title,
"body": body,
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"screen": screen,
},
};
final headers = {
'content-type': 'application/json',
'Authorization': authKey
};
final response = await http.post(Uri.parse(postUrl),
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
return true;
} else {
print(' FCM error');
return false;
}
}
Now for some notifications, I want to send them at 11AM the next day, which I tried to implement using the event_time
parameter of the API as per the code below. However, when I try this code, the notification arrives immediately at the receiver, without the required delay.
Future<bool> callOnFcmApiSendDelayedPushNotifications(String title, String body, List<dynamic> receivers, {String? image = "", String screen = ''}) async {
List<dynamic> tokens = await pushNotificationsManager.getTokens(receivers);
// set time to 11AM next day
DateTime dt = DateTime.now();
DateTime dtTomorrow = DateTime(dt.year, dt.month, dt.day+1, 11);
final postUrl = 'https://fcm.googleapis.com/fcm/send';
Map<String, dynamic> data;
data = {
"registration_ids" : tokens,
"collapse_key" : "type_a",
"notification" : {
"title": title,
"body" : body,
"event_time": Timestamp.fromDate(dtTomorrow).millisecondsSinceEpoch.toString(),
"sound": "default",
"click_action": "FLUTTER_NOTIFICATION_CLICK",
},
'data':{
"title": title,
"body": body,
"event_time": Timestamp.fromDate(dtTomorrow).millisecondsSinceEpoch.toString(),
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"screen": screen,
},
};
final headers = {
'content-type': 'application/json',
'Authorization': authKey
};
final response = await http.post(Uri.parse(postUrl),
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
I know it is possible to send scheduled push notifications from the Firebase console, but is there any way to send a scheduled notification from the app? Note that I am on a free spark plan so cloud functions cannot be used.
Thanks in advance!