0

I'm using stream chat for my app's chat functionality. In which I'm implementing notification.

So when I'm receiving notification in background

FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
  • Above is the function which I call in main.dart.

  • Below is the handler of background message.

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  showLog("firebaseMessagingBackgroundHandler message ===> ${message.data}");
  await Firebase.initializeApp();
  
  final chatClient = StreamChat.of(context).client; //in this line I need context but I can't pass the argument.
  try {
    showLog("in background message received");

    showStreamNotification(message, chatClient);
  } catch (e) {
    showLog(e.toString());
  }
}
Ravin Laheri
  • 801
  • 3
  • 11

2 Answers2

2

You could create a Global key and set it to your MaterialApp and then you could access to the app context from every where in your app.

// create a Global key to be a global variable
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

// set it to your MaterialApp
MaterialApp(
      title: 'App title',
      navigatorKey: navigatorKey,
      ...
    );

// get your app context
final chatClient = StreamChat.of(navigatorKey.currentContext!).client;

Hope this helps.

Hoa Le
  • 174
  • 4
  • 1
    I've tried this thing but when app goes into background it became "null" – Ravin Laheri Mar 30 '23 at 08:49
  • An alternative could be to initialize the `chatClient` object not with the `context`, but with the `apiKey`. This process is described in our extensive guide on [push notifications](https://getstream.io/chat/docs/sdk/flutter/guides/push-notifications/adding_push_notifications_v2/#receiving-notifications). In short you can initialize it like this: `final chatClient = StreamChatClient(apiKey);` – Stefan Blos Mar 30 '23 at 14:23
0

Below thing has solved my issue.

My mistake is that I'm not doing chatClient.connectUser in background message handler.

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  showLog("firebaseMessagingBackgroundHandler message ===> ${message.data}");
  await Firebase.initializeApp();
  
  final chatClient = StreamChatClient(apiKey);

  chatClient.connectUser(
    User(id: userId),
    userToken,  //JWT token
    connectWebSocket: false,
  );

  try {
    showLog("in background message received");

    showStreamNotification(message, chatClient);
  } catch (e) {
    showLog(e.toString());
  }
}
Ravin Laheri
  • 801
  • 3
  • 11