Mr vd
Mr vd

Reputation: 988

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

Upvotes: 5

Views: 12551

Answers (5)

Add Topic Name in Main.dart file

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  FirebaseMessaging fcmMessage = FirebaseMessaging.instance;
  await fcmMessage.subscribeToTopic('testNotification');
  runApp(const MyApp());
}

Add HTTP POST Request

final data = {
      'to': '/topics/testNotification',
      'notification': {
        'body':'Simple Notification',
        'title': 'Test Notification',
        
      }
    };
    String url = 'https://fcm.googleapis.com/fcm/send';
    try {
      final result = await http.post(
        Uri.parse(url),
        body: jsonEncode(data),
        headers: {
          'Content-type': 'application/json',
          'Authorization':
              'key=AAAAm5+++++++++++++++Authorization Token+++++++++++++'
        },
      );
      print(jsonDecode(result.body));
      return jsonDecode(result.body);
    } catch (e) {
      print(e);
      return {'error': e};
    }

Upvotes: 0

Mr vd
Mr vd

Reputation: 988

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");

Upvotes: 9

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

Sending a message to a device require that you call the Firebase Cloud Messaging API and specify the FCM Server Key. As its name implies, this key should only be used on a trusted environment, such as your development machine, a server that you control, or an environment like Cloud Functions. The reason this is required is that anyone who has you FCM server key can send messages to all users of your app.

The simplest way to get started is to simply run a curl command or something like that, calling the legacy FCM REST API. See an example of that here: How can I send a Firebase Cloud Messaging notification without use the Firebase Console? To send to a topic, make sure the to value is something like "/topics/your_topic".

For a more production level, you'll probably want to introduce a server, or use Cloud Functions. Sending a message then becomes a multi-step process like:

  1. The client that wants to send a message, writes that messages to a database, or calls an API.
  2. This write operation triggers your server, or Cloud Functions, which validates the request (determining that this user is authorized to send this message).
  3. The server-side code then calls the Firebase Admin API to send a message to a topic.

For one example of this, see this folder in the functions-samples repo.

Also see:

Upvotes: 5

Ahmed AL-Yousif
Ahmed AL-Yousif

Reputation: 460

According to firebase_messaging readme page, in the last section, you can not send a cloud message using the flutter firebase_messaging library read the Sending Message.

To subscribe a user to a topic:

FirebaseMessaging _firebaseMessaging =  FirebaseMessaging();
_firebaseMessaging.subscribeToTopic("MyTopic");

This will subscribe that device to the topic MyTopic.

You can also unsubscribe by:

_firebaseMessaging.unsubscribeFromTopic("MyTopic");

Upvotes: 1

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126974

You can subscribe to a topic using firebase_messaging and the FirebaseMessaging.subscribeToTopic:

FirebaseMessaging().subcribeToTopic('topic_name');

You can send notifications to a topic using either the Firebase Console or some backend code, e.g. in Cloud Functions.

Learn more.

Upvotes: 3

Related Questions