F.SO7
F.SO7

Reputation: 925

Flutter - routing to a specific screen when app launched through a push notification

I've built an app that sends push notifications using Firebase Cloud Messaging.

Each notification contains data with a user ID, which I want to present a screen using it (for example, presenting the user's profile using the user ID).

I've tried this code:

//NotificationsHandler - a handler for push notifications
class NotificationsHandler {
  static final NotificationsHandler instance = NotificationsHandler();

  final _fcm = FirebaseMessaging();

  //Alot of of other functions including permission handling etc.
  
  void onBackgroundNotificationRecevied({Function onReceived}) {
    _fcm.configure(
      onMessage: onReceived,
      onResume: onReceived,
      onLaunch: onReceived,
    );
  }
}

//MyMainScreen's initState
@override
  void initState() {
    NotificationsHandler.instance.onBackgroundNotificationRecevied(
      onReceived: (message) async {
        final secondScreenUserId = message['data']['userId'];

        await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => SecondScreen(
              secondScreenUserId,
            ),
          ),
        );
      }
    );
    super.initState();
  }

For some reason, when launching the app through the push notification (in both iOS and Android), the first screen (MyMainScreen) does not push the second screen (the MyMainScreen is presented).

Does anyone know why the code above doesn't work? Thank you!

Upvotes: 4

Views: 1530

Answers (1)

M. Hagos
M. Hagos

Reputation: 209

The background handler function be a high-level function, which means you have to delar it outside of the NotificationHandler class you have. Also, you can't have context in backgroundHandler.

Refer to https://firebase.flutter.dev/docs/messaging/overview/ for more on how to handle push notifications.

Upvotes: 1

Related Questions