Flutter使用curl从客户端应用发送通知

时间:2018-09-07 16:55:04

标签: firebase-cloud-messaging flutter

我正在尝试直接从flutter应用程序发送通知,但是我不知道该怎么做。 他们说到处都必须使用基本网络库发送curl请求,但没有示例。

DATA='{"notification": {"body": "this is a body","title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "<FCM TOKEN>"}'

curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=<FCM SERVER KEY>"

请在DART中为我提供示例。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

import 'dart:async';
import 'dart:convert' show Encoding, json;
import 'package:http/http.dart' as http;

class PostCall {
  final postUrl = 'https://fcm.googleapis.com/fcm/send';

  final data = {
    "notification": {"body": "this is a body", "title": "this is a title"},
    "priority": "high",
    "data": {
      "click_action": "FLUTTER_NOTIFICATION_CLICK",
      "id": "1",
      "status": "done"
    },
    "to": "<FCM TOKEN>"
  };

  Future<bool> makeCall() async {
    final headers = {
      'content-type': 'application/json',
      'Authorization': 'key=<FCM SERVER KEY>'
    };

    final response = await http.post(postUrl,
        body: json.encode(data),
        encoding: Encoding.getByName('utf-8'),
        headers: headers);

    if (response.statusCode == 200) {
      // on success do sth
      return true;
    } else {
      // on failure do sth
      return false;
    }
  }
}