Warm tip: This article is reproduced from serverfault.com, please click

Open Flutter app based on notification data?

发布于 2021-01-25 19:20:13

How can I open the flutter app based on notification data using FirebaseMessaging?

So, when I tap on a notification (received through Firebase Messaging), the message handler should evaluate the data and based on them open the app. At the moment it is asynchronous, meaning the app starts and the notification handler continues the work.

It is important to know, that Navigator.push can't be used, as there is an important app setup screen, which checks the auth state and so on at app start. How to solve this issue?

Questioner
Nico
Viewed
0
aqwert 2021-01-26 09:39:35

When you tap a notification from the device's notification centre the operating system will launch the app, provided of course you have set up Firebase messaging correctly as per instructions the onLaunch or onMessage functions will get called.

Now since firebase messaging configured pretty much as early as possible, typically inside the main entry of the flutter app you will need to store the notification somewhere first. This can be a global state object created before anything that uses it.

final notifications = <NotificationData>[]; // globally accessible (i.e. via Provider)

Then in the handler of the messages...

NotificationData onMessage(Map<String, dynamic> data) {
   notifications.add(NotificationData.fromJson(data));
}

The flutter app will start and the MaterialApp will get built. At this point you can have a loading screen to check if the user is authenticated or any new messages in the notifications global state. If there are you can route to a page to display the notification, or get the user to sign in then route to the notification page.