I want the user to land to a specific screen when a notification is tapped from a terminated state. I know that the getInitialMessage()
handles notifications from terminated state but it doesn't seem to navigate to the screen I want.
Here's the code:
AndroidNotificationChannel channel;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
RemoteNotification notification = message.notification;
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: '@drawable/splash',
playSound: true
),
));
navigatorKey.currentState
.push(MaterialPageRoute(builder: (_) => OrdersScreen()));
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
void initState() {
var initializationSettingsAndroid = AndroidInitializationSettings('@drawable/splash');
var initializationSettings = InitializationSettings(android:initializationSettingsAndroid);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage message) {
print('Inside get initial message');
if (message != null) {
print('Inside message not null');
navigatorKey.currentState
.push(MaterialPageRoute(builder: (_) => OrdersScreen()));
}
});
}
}
As you can see, I want to navigate to ordersscreen but I instead land on the landing page. What am I missing? It works fine when the notification is tapped from background state or foreground state, but not from terminated state.