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

时间:2019-06-08 04:50:53

标签: firebase flutter firebase-cloud-messaging

我扑朔迷离地开发了一对一聊天系统,并希望使用FCM向其他设备发送推送通知。

我已经设置了所有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',
        },
      );

但是没有收到推送通知。我必须实现云功能才能发送通知吗?

1 个答案:

答案 0 :(得分:0)

我可以在没有服务器的情况下使用主题/ FCM令牌将FCM消息从一台设备发送到另一台设备。这是代码

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

}

如果您必须使用FCM令牌发送数据请求,请使用

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

希望有帮助