1

I was exploring the way to implement the notification in Flutter. I know we can send the notification using Firebase Console & using the Cloud Functions.

But I got to know about this method of sending the notification directly from flutter app based on action. Just wanted to know more about this, Is it a good way of sending the notification? Can I use this method to send multiple notifications in my production app.

import 'dart:convert';
import 'package:http/http.dart';
import 'package:meta/meta.dart';

class Messaging {
  static final Client client = Client();

  // from 'https://console.firebase.google.com'
  // --> project settings --> cloud messaging --> "Server key"
  static const String serverKey =
      'SERVER_KEY';
  static Future<Response> sendToAll({
    @required String title,
    @required String body,
  }) =>
      sendToTopic(title: title, body: body, topic: 'all');

  static Future<Response> sendToTopic(
          {@required String title,
          @required String body,
          @required String topic}) =>
      sendTo(title: title, body: body, fcmToken: '/topics/$topic');

  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',
        },
      );
}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
vikas pandey
  • 199
  • 2
  • 15
  • I am also interested in this question. – dshukertjr Dec 16 '19 at 04:26
  • *firebaser here* Using `key=$serverKey` in client-side code is a serious security risk, as it allows malicious users to send whatever message they want to your users. This is a bad practice and should not be used in production-level applications. For a better approach, see https://fireship.io/lessons/flutter-push-notifications-fcm-guide/ and my answer here: https://stackoverflow.com/a/57842615 – Frank van Puffelen Dec 16 '19 at 04:53
  • Thanks Frank. This make sense. It try with Cloud Function, I think that would be better. Frank, can I send only some data (means, I don't want to show notification directly from cloud firestore) from cloud function and receive it in my app and then popup the local notification, Is it possible? – vikas pandey Dec 16 '19 at 06:22

0 Answers0