Flutter: How can i send push notification programmatically with fcm

后端 未结 3 1660
野的像风
野的像风 2021-01-01 08:03

I\'m creating a chat application and i want to use fcm to send notification if the person has a new message, but i don\'t know how to proceed. All the tutorials i found use

3条回答
  •  [愿得一人]
    2021-01-01 08:46

    A possible workaround if you use firebase should be like this:

    You need to store each firebase FCM token for a specific user (need to take in account here that a user can log in at the same time on his account from multiple devices) so you can store the userId and his deviceUniqueId on flutter you can get it from device_info https://pub.dev/packages/device_info:

      String identifier;
      final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
      try {
        if (Platform.isAndroid) {
          var build = await deviceInfoPlugin.androidInfo;
          identifier = build.id.toString();
        } else if (Platform.isIOS) {
          var data = await deviceInfoPlugin.iosInfo;
          identifier = data.identifierForVendor;//UUID for iOS
        }
      } on PlatformException {
        print('Failed to get platform version');
      }
    

    and after that to get the unique CFM token that Firebase provide for each device, you can get it using Firebase firebase_messaging plugin (https://pub.dev/packages/firebase_messaging) getToken() and insert the token to firestore (or an other database you want to store it)

      FirebaseMessaging firebaseMessaging = new FirebaseMessaging();
    
      firebaseMessaging.requestNotificationPermissions(
          const IosNotificationSettings(sound: true, badge: true, alert: true));
      firebaseMessaging.onIosSettingsRegistered
          .listen((IosNotificationSettings settings) {
        print("Settings registered: $settings");
      });
    
      firebaseMessaging.getToken().then((token){
    
        print('--- Firebase toke here ---');
        Firestore.instance.collection(constant.userID).document(identifier).setData({ 'token': token});
        print(token);
    
      });
    

    After that you can insert one or more FCM token connected to multiple device for one user. 1 user ... n devices , 1 device ... 1 unique token to get push notifications from Firebase.

    send it automatically when there is a new message for the person : now you need to call the Firestore API(is very fast indeed but need to be careful about the plan limit that you are using here) or another API call if you store the token to another db, in order to get the token/tokens for each user and send the push notifications.

    To send the push notification from flutter you can use a Future async function. P.s: I'm passing as argument a List here in order to use "registration_ids" instead of "to" and send the push notification to multiple tokens if the user has been logged in on multiple devices.

    Future callOnFcmApiSendPushNotifications(List  userToken) async {
    
      final postUrl = 'https://fcm.googleapis.com/fcm/send';
      final data = {
        "registration_ids" : userToken,
        "collapse_key" : "type_a",
        "notification" : {
          "title": 'NewTextTitle',
          "body" : 'NewTextBody',
        }
      };
    
      final headers = {
        'content-type': 'application/json',
        'Authorization': constant.firebaseTokenAPIFCM // 'key=YOUR_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
        print('test ok push CFM');
        return true;
      } else {
        print(' CFM error');
        // on failure do sth
        return false;
      }
    }
    

    You can also check the post call from postman in order to make some tests. POST request On Headers add the:

    1. key Authorization with value key=AAAAO........ // Project Overview -> Cloud Messaging -> Server Key
    2. key Content-Type with value application/json

    And on the body add

    {
     "registration_ids" :[ "userUniqueToken1", "userUniqueToken2",... ],
     "collapse_key" : "type_a",
     "notification" : {
         "body" : "Test post",
         "title": "Push notifications E"
     }
    }
    

    "registration_ids" to send it to multiple tokens (same user logged in to more than on device at the same time) "to" in order to send it to a single token (one device per user / or update always the user token that is connected with his device and have 1 token ... 1 user)

    I'm making an edit to the response, in order to add that is very important to add the FCM Server Key on a trusted environment or server!

提交回复
热议问题