完成一个操作后如何向所有用户动态发送 FirebaseMessaging - Flutter?

How to send FirebaseMessaging dynamically to all users when one action is done - Flutter?

我有一个 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 中的方法中调用它只会向我的 phone 显示通知,而不是向每个 phone 显示通知,有一种方法可以以这种形式进行?

您可以使用云函数执行此操作。通过在创建发布时从您的应用程序调用函数,或者让云函数侦听新文档。请参阅此媒体 post 了解一些想法:https://medium.com/@jerinamathews/send-firebase-cloud-messaging-fcm-to-a-topic-using-cloud-function-when-realtime-database-value-fa78fa758549

更新

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

我没有通过 http post 使用主题,所以我无法确认它是否可行,但我假设如果你可以发送到一个令牌,你必须能够发送到一个主题。