简体   繁体   English

如何使用 FCM 和 Flutter(一个到另一个设备)发送推送通知?

[英]How to send push Notification using FCM and Flutter(One to Another Device)?

I have devloped One to one chat system in flutter and want to send push notification to another device using FCM.我已经在 flutter 中开发了一对一聊天系统,并希望使用 FCM 向另一台设备发送推送通知。

I have setup all the flutter and firebase messaging requirement.我已经设置了所有 flutter 和 firebase 消息传递要求。

//In InitState()
_firebaseMessaging.onTokenRefresh.listen(sendTokenToServer);
    _firebaseMessaging.getToken();
    _firebaseMessaging.configure(onLaunch: (Map<String, dynamic> msg) {
      print("onLaunch");
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Message(this.user, this.event)),
      );
    }, onResume: (Map<String, dynamic> msg) {
      print("onResume");
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Message(this.user, this.event)),
      );
    }, onMessage: (Map<String, dynamic> msg) {
      print("onMessage");
    });
    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, alert: true, badge: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings setting) {
      print("IOS");
    });

//sendTokenToServer() - function send FCM token my Postgres DB

//When user clicks on send Button

Future sendNotification(userData, eventData) async {
    await Messaging.sendToAll(
      title:
          "${toBeginningOfSentenceCase(userData['User']['name'])} on ${toBeginningOfSentenceCase(eventData['Event']['eventName'])} event",
      body: _messageController.text,
      fcmToken: fcmTokenToServer,
    );
  }

//Messaging.sendToAll()
static Future<Response> sendToAll(
          {@required String title,
          @required String body,
          @required String fcmToken}) =>
      sendTo(title: title, body: body, fcmToken: fcmToken);

  static Future<Response> sendTo({
    @required String title,
    @required String body,
    @required String fcmToken,
  }) =>
      client.post(
        'https://fcm.googleapis.com/fcm/send',
        body: json.encode({
          'notification': {'body': '$body', 'title': '$title'},
          'priority': 'high',
          'data': {
            'click_action': 'FLUTTER_NOTIFICATION_CLICK',
            'id': '1',
            'status': 'done',
          },
          'to': '$fcmToken',
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'key=$serverKey',
        },
      );

But No push notification is receiving.但是没有收到推送通知。 Is it that I have to implement cloud functions to send notification??是不是我必须实现云功能才能发送通知??

I could send FCM messages from one device to other with the topic/FCM token without the server.我可以在没有服务器的情况下使用主题/FCM 令牌将 FCM 消息从一台设备发送到另一台设备。

NOTE : Using the server key at client side is a bad practice and should not be used in production-level applications.注意:在客户端使用服务器密钥是一种不好的做法,不应在生产级应用程序中使用。

static Future<bool> sendFcmMessage(String title, String message) async {
    try {
      
      var url = 'https://fcm.googleapis.com/fcm/send';
      var header = {
        "Content-Type": "application/json",
        "Authorization":
            "key=your_server_key",
      };
      var request = {
        "notification": {
          "title": title,
          "text": message,
          "sound": "default",
          "color": "#990000",
        },
        "priority": "high",
        "to": "/topics/all",
      };

      var client = new Client();
      var response =
          await client.post(url, headers: header, body: json.encode(request));
      return true;
    } catch (e, s) {
      print(e);
      return false;
    }
}

If you have to send data request with FCM token, use如果您必须使用 FCM 令牌发送数据请求,请使用

request = {
      'notification': {'title': title, 'body': message},
      'data': {
        'click_action': 'FLUTTER_NOTIFICATION_CLICK',
        'type': 'COMMENT'
      },
      'to': 'fcmtoken'
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当接收方设备未在Android中使用FCM处于前台状态时,如何从设备发送推送通知? - How to send Push Notification from device when the receiver device is not in foreground state using FCM in android? 在 Android 设备上使用 FCM 发送推送通知 - sending push notification using FCM on android device 如何使用 FCM 发送推送通知以响应本机 android 应用程序 - How to send push notification to react native android app using FCM 使用 FCM 按主题进行 Flutter 推送通知 - Flutter push notification using FCM by topic 如何使用 Angular2 使用 FCM 从一台计算机向另一台计算机发送通知 - How to send Notification using FCM from one computer to another using Angular2 如何使用Flutter和Firebase实时数据库发送FCM通知 - How to send fcm notification using flutter and firebase realtime database 如何在flutter中使用javascript云函数发送fcm通知? - How to send a fcm notification using javascript cloud functions in flutter? 如何动态发送 FCM 推送通知? - How to send FCM push notification dynamically? 如何使用 FCM 发送通知? - How to send notification using FCM? 有没有办法使用 FCM 直接向特定设备发送推送通知? - Is there a way to send with FCM a push notification directly to a specific device?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM