Flutter firebase send notification to specific user

Flutter Firebase: Send Notification to Specific User

In order to send a notification to a specific user in Flutter using Firebase Cloud Messaging (FCM), you need to follow these steps:

  1. Create a Firebase project in the Firebase console.
  2. Add the Firebase configuration file to your Flutter project.
  3. Set up Firebase Cloud Messaging in your Flutter project.
  4. Implement logic to handle receiving notifications in your app.
  5. Send a notification to a specific user using the Firebase Cloud Messaging API.

1. Create a Firebase Project

Go to the Firebase console and create a new project. Note down the project ID for later use.

2. Add Firebase Configuration File

Download the JSON configuration file for your Firebase project and place it in the root of your Flutter project. Make sure to update the google-services.json reference in your Flutter android/app/build.gradle file.

3. Set up Firebase Cloud Messaging

Follow the official Flutter documentation to set up Firebase Cloud Messaging in your Flutter project. This involves adding the required dependencies, configuring the Android and iOS apps, and retrieving the device token.

4. Implement Notification Handling

In your Flutter app, you need to implement the logic to listen and handle incoming notifications. You can use the firebase_messaging package provided by Firebase to achieve this.

import 'package:firebase_messaging/firebase_messaging.dart';

class PushNotificationService {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  Future initialize() async {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // Handle incoming notification when the app is in foreground
    });

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      // Handle notification when the app is in background or terminated
    });
  }

  Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    // Handle notification when the app is in background
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  PushNotificationService().initialize();
  runApp(MyApp());
}

5. Send a Notification to a Specific User

To send a notification to a specific user, you need to use the Firebase Cloud Messaging API. You can achieve this by using a server-side implementation, such as Firebase Cloud Functions or your own server.

Here’s an example of sending a notification to a specific user using Firebase Cloud Functions:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const fcm = admin.messaging();

exports.sendNotificationToUser = functions.https.onRequest((request, response) => {
  const userId = request.body.userId; // ID of the user you want to send the notification to

  const message = {
    token: '',
    notification: {
      title: 'New Message',
      body: 'You have a new message!'
    },
    data: {
      // Optional data payload
    }
  };

  fcm.send(message)
    .then(() => {
      response.send('Notification sent successfully');
    })
    .catch((error) => {
      response.status(500).send('Error sending notification: ' + error);
    });
});

In this example, you need to replace <USER_DEVICE_TOKEN> with the device token of the specific user you want to send the notification to. You can fetch the device token from your Flutter app and send it to the server along with the user ID.

Once you have set up the server-side implementation, you can trigger it to send a notification to the specific user whenever needed.

That’s it! With these steps, you can send a notification to a specific user in Flutter using Firebase Cloud Messaging.

Leave a comment