skip to Main Content

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());
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    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());
      }
    }
    

  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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search