如何在flutter中向所有用户推送通知

问题描述 投票:0回答:2

大家好,我想像这样通过 API 向我的 firebase 中的所有用户发送通知:

`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 }));`

android ios iphone flutter visual-studio
2个回答
0
投票

为此你应该使用主题,

需要订阅用户

all
主题,发送通知时不需要token

基于发布/订阅模型,FCM 主题消息传递允许您向已选择加入特定主题的多个设备发送消息。您根据需要撰写主题消息,FCM 处理路由并将消息可靠地传递到正确的设备。

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

和您的数据


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


  
 

0
投票

在 Main.dart 文件中添加主题名称

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

添加 HTTP POST 请求

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};
    }

© www.soinside.com 2019 - 2024. All rights reserved.