With the deprecation of the Cloud Messaging API (Legacy), developers need to migrate to the new Firebase Cloud Messaging API (V1). This guide will help you transition smoothly and demonstrate how to send notifications directly from the client side using a service account JSON.
google-services.json
(for Android) or GoogleService-Info.plist
(for iOS).3. Add Firebase SDK:
pubspec.yaml
, add the necessary Firebase dependencies:dependencies:
firebase_core: latest_version
firebase_messaging: latest_version
http: latest_version
googleapis_auth: latest_version
2. Add Service Account Key to Your Project:
assets
folder of your Flutter project.assets
folder is declared in your pubspec.yaml
:flutter:
assets:
- assets/your-service-account.json
## For <your_project_id> you need to find from firebase console,
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:googleapis_auth/auth_io.dart';
static Future<void> sendTopicNotificationv2() async {
// Load the service account key
final serviceAccountKey = await rootBundle.loadString('assets/your-service-account.json');
final credentials = ServiceAccountCredentials.fromJson(json.decode(serviceAccountKey));
final scopes = ['https://www.googleapis.com/auth/cloud-platform'];
// Get an authenticated HTTP client
final client = await clientViaServiceAccount(credentials, scopes);
final accessToken = (await client.credentials).accessToken.data;
print("AccessToken: $accessToken");
final Map<String, dynamic> notification = {
'title': 'Breaking News',
'body': 'News content here',
};
final Map<String, dynamic> message = {
'topic': '<your_topic>',
'notification': notification,
};
final String url = 'https://fcm.googleapis.com/v1/projects/<your_project_id>/messages:send';
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode(<String, dynamic>{
'message': message,
}),
);
if (response.statusCode == 200) {
print('Notification sent successfully');
} else {
print('Failed to send notification: ${response.statusCode}');
print('Response: ${response.body}');
}
client.close();
}
sendTopicNotificationv2
function from your Flutter app wherever you need to trigger a notification:ElevatedButton(
onPressed: () {
sendTopicNotificationv2();
},
child: Text('Send Notification'),
)
With the deprecation of the legacy Cloud Messaging API, transitioning to FCM V1 is essential for continued support and access to new features. By following these steps, you can send notifications directly from the client side using a service account JSON. This method enhances the flexibility and security of your app, allowing for better integration with Firebase’s robust ecosystem. Happy coding!