skip to Main Content

I assumed I followed all the steps to handling background notifications from firebase in flutter. I have created a top-level function that I am expecting to be triggered whenever a notification comes in. However, the function is never triggered.

Here’s the top-level background handler function that exists in my home page widget but outside the class:

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  // ignore: avoid_print
  print('A background message just showed up :  ${message.messageId}');

  // update SQLite
  var result = await PageService.instance
      .add(PageService.instance.convertToPage(message.data));
  print('added to db: ${result}');
}

Here is my home page init state that calls a function to initialize firebase messgaging:

@override
  void initState() {
    super.initState();

    _initializeFirebaseMessaging();
  }

And then here is the _initializeFirebaseMessaging function that is defined in the home page class as well:

void _initializeFirebaseMessaging() {
    FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      print('new notification arrived');
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;

      // update SQLite
      var result = await PageService.instance
          .add(PageService.instance.convertToPage(message.data));
      print('added to db: ${result}');

      if (notification != null && android != null) {
        // show notification
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                color: Colors.blue,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));
      }
    });
  }

The onmessage.listen works fine as I get notificationd and handle them while I’m in the app, but the background handler is not triggered at all.

I would appreciate any help!

3

Answers


  1. You have to call FirebaseMessaging.onBackgroundMessage inside your main() not in initState()

    Login or Signup to reply.
  2. try: after main func

    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      ...
    }
    

    and remove WidgetsFlutterBinding.ensureInitialized(); in firebaseMessagingBackgroundHandler

    Login or Signup to reply.
  3. onMessage handles foreground notification

    onMessageOpenedApp handles background notification

    Instead of using onMessage for handling Background notifications, add another function block of FirebaseMessaging with onMessageOpenedApp, if you want notification while the app is in background, like this:

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message){...})
    

    onMessage only works when the app is in foreground.
    If you want notification while the app is in the terminated state you can use:

    FirebaseMessaging.instance.getInitialMessage().then((message){...})
    

    Update your firebaseMessagingBackgroundHandler to this:

    Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      await Firebase.initializeApp();
      
      // ignore: avoid_print
      print('A background message just showed up :  ${message.messageId}');
    
      // update SQLite
      var result = await PageService.instance
          .add(PageService.instance.convertToPage(message.data));
      print('added to db: ${result}');
    }
    

    And finally, the main() should look like this:

    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      // Add Firebase Initialization:
      await Firebase.initializeApp();
      // This will initialize a new Firebase instance.
    
      // Background message handler
      FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
      
      runApp(const App());
    }
    

    You should call FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler); from within main(), not from Homepage initState(){}.

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