首页 > 解决方案 > 完成一项操作后如何向所有用户动态发送 FirebaseMessaging - Flutter?

问题描述

我有一个颤振应用程序,在某些时候管理员用户可以保存一份出版物。

现在我希望所有用户在发布该出版物时收到通知(带有标题、描述等)。

我怎么能用firebase消息来做到这一点?

我已经写了这段代码,如果我去firebase控制台并生成一个示例通知,我会正常收到它:

class PushNotificationsManager {

  PushNotificationsManager._();

  factory PushNotificationsManager() => _instance;

  static final PushNotificationsManager _instance = PushNotificationsManager._();

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  Future<void> init() async {
    if(Platform.isIOS){
      _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings());
    }
    _firebaseMessaging.configure(
      // Called when the app is in the foreground and we receive a push notif.
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
        print(message['notification']['body']);

      },
      // Called when the app has been closed completely and its opened
      // from the notification directly
      onLaunch: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
      },
      // Called when the app is in the background and its opened from the notif
      onResume: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
      },
    );
}

总之,当管理员创建新出版物而不去firebase控制台手动生成通知时,我如何向所有用户生成通知(创建标题和描述)?

更新 我试图这样做:

Future sendNotification() async {
    final String url = 'https://fcm.googleapis.com/fcm/send';
    var token = await _firebaseMessaging.getToken();
    var data;
    data='{"notification": {"body": "this is a body", "title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK"}, "to": "${token}"}';
    final response = await http.post(
      url,
      headers: <String, String>{"Content-Type": "application/json", "Keep-Alive" : "timeout=5", "Authorization" : "key=${mykey}"},
      body: data
    );

    print(response.body);
  }

...在我将事件保存在firebase中的方法中调用它只会向我的手机显示通知,而不是向每部手机显示通知,有没有办法以这种形式做到这一点?

标签: firebaseflutterdartpush-notificationfirebase-cloud-messaging

解决方案


您可以使用云功能来做到这一点。通过在创建发布时从您的应用程序调用该函数,或者让云函数侦听新文档。有关一些想法,请参阅此 Medium 帖子:https ://medium.com/@jerinamathews/send-firebase-cloud-messaging-fcm-to-a-topic-using-cloud-function-when-realtime-database-value-fa78fa758549

更新

根据您的更新,我建议您考虑使用“主题”而不是特定令牌(仅适用于一个设备)。要使用主题,您需要确保所有用户在打开应用程序时自动订阅所选主题(他们每次可以订阅相同的主题,没有负面影响)。FCM 维护一个针对该主题的订阅设备令牌列表。

我没有通过 http 帖子使用主题,所以我无法确认这是可能的,但我假设你是否可以发送到令牌,你必须能够发送到主题。


推荐阅读