/ SDKs / Flutter
SDKs
Chat SDKs Flutter v3
Chat SDKs Flutter
Chat SDKs
Flutter
Version 3
Sendbird Chat SDK v3 for Flutter is no longer supported as a new version is released. Check out our latest Chat SDK v4

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) notificatons.


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.
dependencies:
  firebase_messaging: ^14.1.1
  1. Then, install the flutter_local_notifications package.
dependencies:
  flutter_local_notifications: ^12.0.2
  1. Add Firebase core.
dependencies:
  firebase_core: ^2.0.0
  1. Initialize Firebase in the main function before running the client app.
Future<void> main() async {
 WidgetsFlutterBinding.ensureInitialized();
 await Firebase.initializeApp();
 return runApp(const MyApp());
}
  1. Then, instantiate Firebase messaging.
   _messaging = FirebaseMessaging.instance;
  1. Create firebaseMessagingBackgroundHandler to handle messages when the client app is in the background.
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
 print("Handling background message: ${message.messageId}");
 NotificationService.showNotification(
   message.notification?.title ?? '',
   message.notification?.body ?? '',
 );
}
  1. You can set up local notification to receive notifications when the client app is in the foreground using the following code.
// Enable notification when app is in the foreground in firebase messaging for iOS.
   await FirebaseMessaging.instance
       .setForegroundNotificationPresentationOptions(
     alert: true, // Required to display a heads up notification
     badge: true,
     sound: true,
   );
  // On iOS devices, the following code lets you obtain the user permissions.
   NotificationSettings settings = await _messaging.requestPermission(
     alert: true,
     badge: true,
     provisional: false,
     sound: true,
   );
  1. You can get either a FCM push token if using an Android device or an APNs push token if using an iOS device and register the push token to the Sendbird server. If using an iOS device, you should grant permission to receive notifications on your device.
_sendbird.registerPushToken(
         type: kIsWeb
             ? PushTokenType.none
             : Platform.isIOS
                 ? PushTokenType.apns
                 : PushTokenType.fcm,
         token: token,
       );


   if (settings.authorizationStatus == AuthorizationStatus.authorized) {
     print('User granted permission');
     String? token;

     if (Platform.isIOS) {
       // Retrieve a push token for iOS.
       token = await _messaging.getAPNSToken();
     } else {
       // Retrieve a push token for FCM.
       token = await _messaging.getToken();
     }
  1. You can handle notifications received using the following code.
// Handle the notifications received.
     FirebaseMessaging.onMessage.listen((RemoteMessage message) {
       print('title: ${message.notification?.title}');
       print('body: ${message.notification?.body}');
       // Parse the message received.
       PushNotification notification = PushNotification(
         title: message.notification?.title,
         body: message.notification?.body,
       );

       setState(() {
         _notificationInfo = notification;
         _totalNotifications++;
       });
       if (_notificationInfo != null) {
         NotificationService.showNotification(
             _notificationInfo?.title ?? '', _notificationInfo?.body ?? '');
       }
     });

Note: To learn more about the installation process, see Firebase Messaging Plugin for Flutter or APNs push.

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 notification 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 > Chat > Push 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
    },
}