Home > Mobile >  Is there a way to send Cloud Messages or Push Notifications to a Flutter App from C#?
Is there a way to send Cloud Messages or Push Notifications to a Flutter App from C#?

Time:07-11

For my use case, a user from C# WinForm desktop application generates some data (creates a new document in a collection named "Requests" in Firestore). What I want is that whenever a new document is created/added in the Requests collection, a notification is sent to the Flutter app. I am looking for some guidelines for a workaround regarding this using C#.

CodePudding user response:

I assume that you have already connected your C# software with firebase as backend. If that is the case then:

1- First connect your flutter app to firebase. Follow this link to do so: Connect flutter app to firebase

2- Use this link to learn and create your first cloud function on firebase. Create first cloud function from flutter app terminal

3- Now you are in the position to create a cloud function with which a notification will be generated to the device you want on the creation of document in the request collection.

4- Deploy this function on your firebase to send notification to your required device.

exports.sendFirstNotification =
  functions.firestore.document('/Requests/{documentId}')
    .onCreate(async (snap, context) => {
var name = "Bilal Saeed";

  var myDeviceToken = snap.data().fcmToken;
// You need this token for push notification on a device.
// Each device has its own token.
// Access it in this function. 
//If you are working on C# software then create your token from flutter app
 //and save it on firestore. And access that token here and save it in myDeviceToken variable.
// Currently in this function its assumed that, the newly document created //in your Request collection contains the device token which is being //assigned to myDeviceToken variable.

  await admin.messaging().send({
    token: myDeviceToken,
    notification: {
         title: `Hi, you received first notification by the help of ${name}`,
         body: " Upvote his answer if he really helped you!"
        },
    
  }).then(value => {
    functions.logger.log("First notification sent to the device");
  }).catch((e) =>{
    functions.logger.log(e.toString());
  });
});

Use this command from terminal to deploy your this function.

firebase deploy --only functions:sendFirstNotification

Now create the document from your C# software and you will get the notification on your flutter app mobile device on the creation of document in Requests Collection. Congrats!

  • Related