Sending Push Notifications from Firebase to Flutter Applications Via REST [June 2024]

M. salah
3 min readJun 5, 2024

--

πŸ‡ΈπŸ‡© πŸ‡΅πŸ‡Έ Pray for Sudan and Gaza πŸ‡ΈπŸ‡© πŸ‡΅πŸ‡Έ

Note: This article is a summary of a long conversation with ChatGPT, and the purpose of sharing it is to benefit and facilitate use later.

Push notifications are a vital part of modern mobile applications, keeping users engaged and informed. This article will guide you through the process of implementing push notifications in a Flutter application using Firebase Cloud Messaging (FCM). We will create a Dart service to handle the authentication and sending of notifications.

Prerequisites

Before diving into the code, ensure you have the following setup:

  1. A Flutter application.
  2. A Firebase project with Cloud Messaging enabled.
  3. Service account credentials for the Firebase project.

Step-by-Step Implementation

1. Setting Up the Service Account

First, download the service account JSON file from your Firebase project settings and note down the client_email and private_key from the file. These will be used for authentication.

2. Installing Dependencies

Add the necessary dependencies to your pubspec.yaml file:

dependencies:
http: ^0.13.3
dart_jsonwebtoken: ^2.1.0

Run flutter pub get to install the packages.

3. Creating the Notification Service

Create a new Dart file (e.g., notification_service.dart) and add the following code:

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
class NotificationService {
final String serverUrl =
'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send';
Future<String> _getAccessToken() async {
const clientEmail =
"your-client-email@your-project-id.iam.gserviceaccount.com";
const privateKey =
"-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY\n-----END PRIVATE KEY-----\n";
final iat = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final exp = iat + 3600;
// Create a JWT
final jwt = JWT(
{
'iss': clientEmail,
'scope': 'https://www.googleapis.com/auth/cloud-platform',
'aud': 'https://oauth2.googleapis.com/token',
'iat': iat,
'exp': exp,
},
);
// Sign the JWT with the private key
final token = jwt.sign(
RSAPrivateKey(privateKey),
algorithm: JWTAlgorithm.RS256,
);
// Request an access token
final response = await http.post(
Uri.parse('https://oauth2.googleapis.com/token'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token,
},
);
if (response.statusCode == 200) {
final responseData = jsonDecode(response.body);
return responseData['access_token'];
} else {
throw Exception('Failed to obtain access token: ${response.body}');
}
}
Future<void> sendPushMessage({
required String token,
required String title,
required String body,
}) async {
final accessToken = await _getAccessToken();
try {
final response = await http.post(
Uri.parse(serverUrl),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode(
{
'message': {
'token': token,
'notification': {
'title': title,
'body': body,
},
},
},
),
);
if (response.statusCode == 200) {
print('Push message sent successfully');
} else {
print('Failed to send push message: ${response.statusCode}');
print('Response: ${response.body}');
}
} catch (e) {
print('Error sending push message: $e');
}
}
}

4. Using the Notification Service

In your Flutter application, you can now use the NotificationService to send push notifications. For instance:

void main() {
NotificationService notificationService = NotificationService();
notificationService.sendPushMessage(
token: 'recipient-device-token',
title: 'Hello!',
body: 'This is a test notification',
);
}

Explanation of the Code

  1. Dependencies: We use the http package for making HTTP requests and dart_jsonwebtoken for creating JSON Web Tokens (JWT).
  2. Service URL: The serverUrl is the endpoint for sending messages through FCM. Replace your-project-id with your actual Firebase project ID.
  3. Authentication: The _getAccessToken method creates a JWT using the service account credentials and exchanges it for an access token from Google OAuth2.
  4. Sending Notifications: The sendPushMessage method constructs the notification payload and sends it to the FCM endpoint using the access token.
  5. Error Handling: The code includes basic error handling for both the access token retrieval and message sending processes.

Conclusion

This guide covered the implementation of a Dart service to send push notifications from Firebase to a Flutter application. By following these steps, you can enhance your app with real-time notifications, improving user engagement and retention. For further customization and handling of notification actions, refer to the official Firebase and Flutter documentation.

Contact Information

For any queries or further assistance, feel free to reach out:

--

--