/ SDKs / Flutter
SDKs
Chat SDKs Flutter v4
Chat SDKs Flutter
Chat SDKs
Flutter
Version 4

Set up push notifications

Copy link

To notify users of events that take place on a client app, you should set up notifications first. You can follow the steps below to set up Firebase Cloud Messaging (FCM) or Apple Push Notification service (APNs) notifications.


Set up notification services

Copy link

Step 1 Get a push token to register to the Sendbird server

Copy link

You should set up FCM to receive notifications, whether you are using iOS or Android devices.

  1. Install firebase_messaging package.
dependencies:
  firebase_messaging: ^14.4.1
  firebase_core: ^2.10.0
  1. Initialize Firebase in the main function before running the client app.
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
  1. You can handle notifications when the client app is in the background using the following code.
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // Background message
}

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  1. You can handle notifications when the client app is in the foreground using the following code.
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  // Foreground message
});
  1. Register the push token to the Sendbird server.
await SendbirdChat.registerPushToken(
  type: _getPushTokenType(),
  token: await _getToken(),
  unique: true,
);

PushTokenType? _getPushTokenType() {
  PushTokenType? pushTokenType;
  if (Platform.isAndroid) {
    pushTokenType = PushTokenType.fcm;
  } else if (Platform.isIOS) {
    pushTokenType = PushTokenType.apns;
  }
  return pushTokenType;
}

Future<String?> _getToken() async {
  String? token;
  if (Platform.isAndroid) {
    token = await FirebaseMessaging.instance.getToken();
  } else if (Platform.isIOS) {
    token = await FirebaseMessaging.instance.getAPNSToken();
  }
  return token;
}

Note: To learn more about the installation process, see Firebase Messaging Plugin for Flutter. If the firebase_messaging package does not work well, you can use other packages like push. You can also refer to our sample regarding this. To test push notifications with our sample, you have to add your firebase app for Android and iOS each on Firebase Console. Then, replace android/app/google-services.json with your file for Android and bundleId with your bundleId for iOS.

Step 2 Register credentials for FCM or APNs to the Sendbird server

Copy link

The FCM server requires a registration token while APNs expects an authentication token or a certificate when sending a push notification to a particular device. A user can have up to 20 device tokens for each push notification service. If the user has more than 20 device tokens, the oldest token is deleted before a new one is added. As a result, only the most recent 20 tokens are maintained.

  • FCM: Register a server key and a registration token on Sendbird Dashboard. To learn more, see Push notifications in our Docs for Android.

  • APNs: Create a SSL certificate and export a .p12 certificate or a .p8 authentication token. Then upload the file and register a device token on Sendbird Dashboard. To learn more, see Push notifications in our Docs for iOS.

Step 3 Handle a notification payload

Copy link

The Sendbird server sends notification requests with a payload in JSON format to one of the push notification services. Depending on the service you are using for push notifications, the way to handle the payload may differ. To learn more, see handle a notification payload section for FCM or APNs.

A notification message payload may consist of two properties, which are message and sendbird. The message property is a string generated according to a push notification content template you set on Sendbird Dashboard. The sendbird property is a JSON object which contains all the information about the message a user has sent. The following is a complete payload format of the sendbird property, and it contains a set of provided key-value items. It has the full set of information about the push notification. For example, the value of the message key is the content of the text message received.

Note: To add to or remove from the payload the members and channel_unread_count properties, go to Settings > Application > Notifications on Sendbird Dashboard.

{
  "category": "messaging:offline_notification",
  "type": string,               // Message type: MESG, FILE, or ADMM
  "message": string,            // User input message
  "custom_type": string,        // Custom message type
  "message_id": long,           // Message ID
  "created_at": long,           // The time that the message was created, in a 13-digit Unix milliseconds format
  "app_id": string,             // Application's unique ID
  "unread_message_count": int,  // Total number of new messages unread by the user
  "channel": {
    "channel_url": string,      // Group channel URL
    "name": string,             // Group channel name
    "custom_type": string,      // Custom Group channel type
    "channel_unread_count": int // Total number of unread new messages from the specific channel
  },
  "channel_type": string,       // The value of channel_type is set by the system.
                                // The value of messaging indicates a distinct group channel
                                // while group_messaging indicates a private group channel
                                // and chat indicates all other channel types.
  "sender": {
    "id": string,               // Sender's unique ID
    "name": string,             // Sender's nickname
    "profile_url": string,      // Sender's profile image URL
    "require_auth_for_profile_image": false,
    "metadata": {}
  },
  "recipient": {
    "id": string,               // Recipient's unique ID
    "name": string              // Recipient's nickname
  },
  "files": [],                  // An array of data regarding the file message, such as filename
  "translations": {},           // The items of locale:translation.
  "push_title": string,         // Title of a notification message that can be customized
                                // on Sendbird Dashboard with or without variables.
  "push_sound": string,         // The location of a sound file for notifications
  "audience_type": string,      // The type of audiences for notifications
  "mentioned_users": {
    "user_id": string,          // The ID of a mentioned user
    "nickname": string,         // The nickname of a mentioned user
  "profile_url": string,        // Mentioned user's profile image URL
    "require_auth_for_profile_image": false
  },
}