Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To display stream chat notification background with the use of FirebaseMessaging.onBackgroundMessage, follow these steps:

  1. Set up Firebase Cloud Messaging (FCM) in your Stream Chat application by adding the necessary SDKs and registering your app with FCM.

  2. Create a new file in your project named firebase_messaging.dart and add the following code:

import 'dart:io';
import 'dart:convert';

import 'package:firebase_messaging/firebase_messaging.dart';

FirebaseMessaging messaging = FirebaseMessaging.instance;

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('Handling a background message ${message.messageId}');

  // TODO: Handle the message - this can be anything you want to do with it.
}

void initializeFirebaseMessaging() {
  if (Platform.isIOS) {
    messaging.requestPermission();
  }

  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
}
  1. Call initializeFirebaseMessaging() on app startup to register your background message handler with Firebase Messaging.

  2. When receiving a chat notification, make sure to include a data payload in your notification message that contains the necessary information to display the chat notification. For example:

{
  "to": "your-device-token",
  "data": {
    "title": "New Message from John",
    "body": "Hey, how's it going?",
    "chat_id": "1234"
  }
}
  1. In firebaseMessagingBackgroundHandler(), retrieve the necessary information from the data payload and use it to display the chat notification background. For example:
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('Handling a background message ${message.messageId}');
  final data = jsonDecode(message.data['data']);
  final chatId = data['chat_id'];
  final title = data['title'];
  final body = data['body'];

  // TODO: Use the chatId, title, and body to display the chat notification here.
}