DEV Community

zeeshan mehdi
zeeshan mehdi

Posted on • Edited on

how to send push notification to particular user using fcm (firebase Messaging) and Flutter

Notification Sending Side Using Dio flutter Library to make http post request

step1 : Get api key from firebase console under firebase messaging section or from project settings.

var postUrl = "fcm.googleapis.com/fcm/send";

        static Future<void> sendNotification(receiver,msg)async{

        var token = await getToken(receiver);
        print('token : $token');

        final data = {
          "notification": {"body": "Accept Ride Request", "title": "This is Ride Request"},
          "priority": "high",
          "data": {
            "click_action": "FLUTTER_NOTIFICATION_CLICK",
            "id": "1",
            "status": "done"
          },
          "to": "$token"
        };

        final headers = {
          'content-type': 'application/json',
          'Authorization': 'key=<Your firebase Messaging Api Key Get it from firebase project settings under cloud messaging section>'
        };


        BaseOptions options = new BaseOptions(
          connectTimeout: 5000,
          receiveTimeout: 3000,
          headers: headers,
        );


        try {
          final response = await Dio(options).post(postUrl,
              data: data);

          if (response.statusCode == 200) {
            Fluttertoast.showToast(msg: 'Request Sent To Driver');
          } else {
            print('notification sending failed');
            // on failure do sth
          }
        }
        catch(e){
          print('exception $e');
        }




      }

      static Future<String> getToken(userId)async{

        final Firestore _db = Firestore.instance;

        var token;
        await _db.collection('users')
            .document(userId)
            .collection('tokens').getDocuments().then((snapshot){
              snapshot.documents.forEach((doc){
                token = doc.documentID;
              });
        });

        return token;


      }


    //Now Receiving End 

        class _LoginPageState extends State<LoginPage>
        with SingleTickerProviderStateMixin {

      final Firestore _db = Firestore.instance;
      final FirebaseMessaging _fcm = FirebaseMessaging();

      StreamSubscription iosSubscription;



    //this code will go inside intiState function 

    if (Platform.isIOS) {
          iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
            // save the token  OR subscribe to a topic here
          });

          _fcm.requestNotificationPermissions(IosNotificationSettings());
        }
        _fcm.configure(
          onMessage: (Map<String, dynamic> message) async {
            print("onMessage: $message");
            showDialog(
              context: context,
              builder: (context) => AlertDialog(
                content: ListTile(
                  title: Text(message['notification']['title']),
                  subtitle: Text(message['notification']['body']),
                ),
                actions: <Widget>[
                  FlatButton(
                    child: Text('Ok'),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                ],
              ),
            );
          },
          onLaunch: (Map<String, dynamic> message) async {
            print("onLaunch: $message");
            // TODO optional
          },
          onResume: (Map<String, dynamic> message) async {
            print("onResume: $message");
            // TODO optional
          },
        );

//saving token while signing in or signing up
 _saveDeviceToken(uid) async {
    FirebaseUser user = await _auth.currentUser();

    // Get the token for this device
    String fcmToken = await _fcm.getToken();

    // Save it to Firestore
    if (fcmToken != null) {
      var tokens = _db
          .collection('users')
          .document(uid)
          .collection('tokens')
          .document(fcmToken);

      await tokens.setData({
        'token': fcmToken,
        'createdAt': FieldValue.serverTimestamp(), // optional
        'platform': Platform.operatingSystem // optional
      });
    }
  }

Enter fullscreen mode Exit fullscreen mode

libs used firebase messaging, Dio for http request and firestore to store and retrieve fcm token.

Top comments (15)

Collapse
 
zeeshanmehdi profile image
zeeshan mehdi

final headers = {
'content-type': 'application/json',
'Authorization': 'key=AAAAY2mZqb4:APA91bH38d3b4mgc4YpVJ0eBgDez1jxEzCNTq1Re6sJQNZ2OJvyvlZJYx7ZASIrAj1DnSfVJL-29qsyPX6u8MyakmzlY-MRZeXOodkIdYoWgwvPVhNhJmfrTC6ZC2wG7lcmgXElA6E09'
};

get this key from firebase project under firebase massaging

Collapse
 
roshdialmajzoub profile image
roshdiAlMajzoub

hii please can you help me
i want to send notification to specific users
i did what you did but i am getting http status error [520]

Thread Thread
 
zeeshanmehdi profile image
zeeshan mehdi

this error means you are being sent an empty response. there is something that you are missing in the request.
please ensure these points
checklist

  • header
  • token ( of receivers device)
  • fcm send url is valid
  • body is in the json format
Thread Thread
 
roshdialmajzoub profile image
roshdiAlMajzoub

Now i am getting on the terminal that fcm request for device sent but i am not getting any notificstion

Thread Thread
 
zeeshanmehdi profile image
zeeshan mehdi

configure receiving end well. there might be issues on receiving end now

Thread Thread
 
roshdialmajzoub profile image
roshdiAlMajzoub

How can i solve it?

Thread Thread
 
zeeshanmehdi profile image
zeeshan mehdi

logout and relogin on receiving device, make sure token is same and valid. in console you can print out if it is inside onlaunch ,onMessage or onResume if one of these methods is getting triggered on receiver app that means something is wrong with your implementation

Thread Thread
 
zeeshanmehdi profile image
zeeshan mehdi

share a screenshot of your console

Thread Thread
 
roshdialmajzoub profile image
roshdiAlMajzoub

Can you show me a sample code about it?

Thread Thread
 
zeeshanmehdi profile image
zeeshan mehdi

_fcm.configure(
onMessage: (Map message) async {
print("onMessage: $message");
showDialog(
context: context,
builder: (context) => AlertDialog(
content: ListTile(
title: Text(message['notification']['title']),
subtitle: Text(message['notification']['body']),
),
actions: [
FlatButton(
child: Text('Ok'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
},
onLaunch: (Map message) async {
print("onLaunch: $message");
// TODO optional
},
onResume: (Map message) async {
print("onResume: $message");
// TODO optional
},
);

Thread Thread
 
roshdialmajzoub profile image
roshdiAlMajzoub

Where i put these stuff?!!

Thread Thread
 
zeeshanmehdi profile image
zeeshan mehdi

in your home page initstate method

Collapse
 
codermanuel profile image
Coder-Manuel

Nice Stuff...

Collapse
 
zeeshanmehdi profile image
zeeshan mehdi
Collapse
 
tamilselvan943 profile image
TAMILSELVAN943

Hi i need explain deeply.Can u help me