Home > Back-end >  how to push notification to all users in flutter like
how to push notification to all users in flutter like

Time:04-20

hello guys i want to send notification to all users in my firebase by API like this :

`var serverToken ="" ;

sendNotify(String title , String body , String id) async{

await http.post(

Uri.parse('https://fcm.googleapis.com/fcm/send'),

headers:<String,String>{'Content-Type':'application/json', 'Authorization':'key=$serverToken',},

body:jsonEncode(

<String,dynamic>{

'notification':<String,dynamic>{

  'body':body.toString(),

  'title':title.toString()

},

'priority':'high',

'data':<String,dynamic>{

  'click_action':'FLUTTER_NOTIFICATION_CLICK',

  'id':id.toString()},

//'to':'all', <<<<<<< here i want to send it to all users not by token }));`

CodePudding user response:

For this you should use topics ,

You need to subscribe users to the all topic and no need for tokens when sending the notification

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.

// subscribe to topic on each app start-up
await FirebaseMessaging.instance.subscribeToTopic('all');

and your data


jsonEncode({
     'topic': "all",
    'data': {
      'via': 'FlutterFire Cloud Messaging!!!',
      'count': _messageCount.toString(),
    },
    'notification': {
      'title': 'Hello FlutterFire!',
      'body': 'This notification (#$_messageCount) was created via FCM!',
    },
  });


  
 
  • Related