Chat Flutter v3
Chat Flutter
Chat
Flutter
Home
/
Chat
/
Flutter

Push notifications

A push notification is a message that is immediately delivered to a user's device when the device is either idle or running the client app in the background. Push notifications for Flutter client apps can be sent using Firebase Cloud Messaging (FCM) or Apple Push Notification service (APNs) which contains custom data that your app needs in order to respond to the notifications. When a message is sent to the Sendbird server through our Chat SDK for Flutter, the server communicates with the FCM or APNs with a push notification payload. Then, the FCM or APNs delivers a push notification to mobile devices where the client app is installed.

Notifications can be configured to display an alert, play a sound, or place a badge your app's icon and are only applicable to group channels, not open channels.


Step 1: Install a package

First, install a package of your choice in order to send push notifications to users.

FCMAPNs
// Run this command and create a dependency.
$ flutter pub add firebase_messaging

// Once the dependency is created, use the following code to import the package.
import 'package:firebase_messaging/firebase_messaging.dart';

Note: For further instruction on installation, visit Firebase Messaging Plugin for Flutter or APNs push.

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

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.

Note: 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 taken will be deleted before a new token is added. In result, only the 20 newest tokens will be maintained.

  • FCM: Register a server key and a registration token on the 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 them and register a device token on the Sendbird Dashboard. To learn more, see Push notifications in our Docs for iOS.

Step 3: Handle a notification payload

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 the Handle a notification payload section for FCM or APNs.

A notification message payload may consist of two properties: message and sendbird. The following is a complete payload format of the sendbird property, which 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 means a received text message.

Note: The members and channel_unread_count properties can be added into or removed from the payload in Settings > Application > Notifications on the 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 'messaging' indicates a distinct group channel while 'group_messaging' indicates a private group channel and 'chat' indicates all other cases.
    "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 in the 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
    },
}

Push notification content templates

Push notification content templates are pre-formatted forms that can be customized to display your own push notification messages on a user’s device. Sendbird provides two types: default and alternative. Both templates can be customized from the Sendbird Dashboard by going to Settings > Application > Notifications > Push notification content templates.

Content templates

There are two types of push notification content template: Default and Alternative. Default template is a template that applies to users with the initial notification message setting. Alternative template is used when a user selects a different notification content template instead of the default template.

The content in the template is set at the application level while the selection of templates is determined by a user or through the Chat Platform API.

Note: When a custom channel type has its own customized push notification content template, it takes precedence over the default or alternative templates.

Both templates can be customized using the variables of sender_name, filename, message, channel_name, and file_type_friendly which will be replaced with the corresponding string values. As for the file_type_friendly, it will indicate the type of the file sent, such as audio, image, and video.

List of content templates

Refer to the following table for the usage of content templates:

Text messageFile message

Default template

{sender_name}: {message} (ex. Cindy: Hi!)

{filename} (ex. hello_world.jpg)

Alternative template

New message arrived

New file arrived

To apply a template to push notifications, use the setPushTemplate() method. Specify the template name as either with sbPushTemplateDefault or sbPushTemplateAlternative.

try {
    await sendbird.setPushTemplate(sbPushTemplateAlternative);
} catch (e) {
    // Handle error.
}

To check the current user's push notification template, use the getPushTemplate() method like the following:

try {
    final template = await sendbird.getPushTemplate();
    if (template == sbPushTemplateDefault) {
        // Currently configured to use the default template.
    } else if (template == sbPushTemplateAlternative) {
        // Currently configured to use the alternative template.
    }
} catch (e) {
    // Handle error.
}

Push notification tester

After registering a credential for push notification services, you can test whether push notification credentials and notification services work properly through Sendbird Dashboard.

In Settings > Notifications > Push notification services on the dashboard, each credential has a Send button that allows you to send a test message. The test message will be sent to a target user and their device, which sets off a push notification on the device. At the same time, a new group channel will be created for this test, containing only the target user. If you've already tested push notification with the same target user and the same target device token, the message will be sent to the existing test channel.

Note: If there is another member in the test channel or the target user has left the channel, delete the test channel before carrying out a test.

  1. Go to Settings > Notifications > Push notification services on the Sendbird Dashboard. Find a Send button in the right-end column of each table.

  1. You can search a target user by either their User ID or Nickname in the popup window. Once a user is selected, choose a target device from a list of device tokens linked to the user.

  1. Double check to see if you've selected a correct device token of the user because this push notification will show up on an actual mobile device. Confirm the target channel name and URL, then send the message.

Note: If this is your first test, a new test channel will be created. For future tests with the same target user and the same target device token, the name and URL of the existing test channel will show above the message box.

  1. Check to see if the push notification arrived on the mobile device or emulator. The test message will state the time when Sendbird server sent the message.
Test message sent at {HH:MM:SS} on {MM-DD-YYYY}

Note: In order to display push notifications on Android devices and emulators, an additional implementation is required in the client app. To learn more, see Push notification for FCM or Push notification for HMS. For iOS devices, only an actual mobile device can receive push notifications while emulators can't.


Push notification translation

Push notification translation allows your users to receive notification messages in their preferred languages. Users can set up to four preferred languages. If messages are sent in one of those languages, the notification messages won’t be translated. If messages are sent in a language other than the preferred languages, the notification messages will be translated into the user's first preferred language. In addition, the messages translated into other preferred languages will be provided in the sendbird property of a notification message payload.

Note: A specific user's preferred languages can be set with our platform API's update a user action.

The current user's preferred languages can be set using the updateCurrentUserInfoWithPreferredLanguages() method as follows:

final preferredLanguages = ['fr', 'de', 'es', 'ko'];    // French, German, Spanish, and Korean

try {
    await sendbird.updateCurrentUserInfo(
        preferredLanguages: preferredLanguages
    );
} catch (e) {
    // Handle error.
}

If successful, the following notification message payload will be delivered to the current user's device.

{
    "message": {
        "token": "ad3nNwPe3H0:ZI3k_HHwgRpoDKCIZvvRMExUdFQ3P1...",
        "notification": {
            "title": "Greeting!",
            "body": "Bonjour comment allez vous"    // A notification message is translated into the first language listed in the preferred languages.
        }
    },
    "sendbird": {
        "category": "messaging:offline_notification",
        "type": "User",
        "message": "Hello, how are you?",
        ...

        "translations": {                           // The translated messages in other preferred languages.
            "fr": "Bonjour comment allez vous",
            "de": "Hallo wie geht es dir",
            "es": "Hola como estas",
            "kr": "안녕하십니까?"
        },

        ...
    }
}