Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send notification to a Topic

I want a code to send notification from one device to multiple devices on a specific topic and I want to show that notification on devices who subscribe to that topic? I will use firestore to store data and store tokens and also use Firebase messaging to send notifications

like image 288
Mr vd Avatar asked Dec 05 '22 09:12

Mr vd


1 Answers

This is my code to send notification on particular topic

I hope this helps the new developer.

import 'package:http/http.dart' as http;

Future<void> sendNotification(subject,title) async{

final postUrl = 'https://fcm.googleapis.com/fcm/send';

String toParams = "/topics/"+'yourTopicName';

final data = {
"notification": {"body":subject, "title":title},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"sound": 'default',
"screen": "yourTopicName",
},
"to": "${toParams}"};

final headers = {
'content-type': 'application/json',
'Authorization': 'key=key'

};

final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);

if (response.statusCode == 200) {
// on success do 
print("true");
} else {
// on failure do 
print("false");

}
}

Subscribe by using

FirebaseMessaging _firebaseMessaging =  FirebaseMessaging();
_firebaseMessaging.subscribeToTopic("yourTopicName");
like image 113
Mr vd Avatar answered Jan 09 '23 16:01

Mr vd