sendNotification static method
Implementation
static Future<void> sendNotification({
required List<dynamic> deviceTokens,
required String title,
required String message,
required String image,
}) async {
final String serverKey = await getAccessToken();
String endpointFirebaseCloudMessaging =
'https://fcm.googleapis.com/v1/projects/chat-application-real-time/messages:send';
for (String deviceToken in deviceTokens) {
final Map<String, dynamic> notificationMessage = {
'message': {
'token': deviceToken,
'notification': {
'title': title,
'body': message,
'image': image,
},
'data': {
'name': 'name',
'title': title,
'message': message,
'image': image,
}
}
};
try {
final http.Response response = await http.post(
Uri.parse(endpointFirebaseCloudMessaging),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $serverKey'
},
body: jsonEncode(notificationMessage),
);
if (response.statusCode == 200) {
print("Notification sent successfully to device token: $deviceToken");
} else {
print(
"Notification not sent to device token $deviceToken: ${response.body}");
}
} catch (e) {
print("Error sending notification to device token $deviceToken: $e");
}
}
}