In one of my app want notification handling based on id, whether it is foreground or background. I'm not able to manage it.
What i want is when i receive the push notification, user should be navigated to the respective screens. even if we are on any of the current screen or app is in background. I also have splash screen in between. So, how can i manage the navigation even if i have somethings to fetch from web api and then navigate to some other screen.
I am getting push notification every time whether app is in foreground or background mode. Also, any of the toasts are not shown when notifications are received as per my following code.
I have added following code for notification handling,
final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
BuildContext _context;
setupFirebaseMessaging() async {
if (Platform.isIOS) {
await _firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(
sound: true, badge: true, alert: true, provisional: false),
);
}
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage called : ${message.toString()}");
notiMessage = message;
getLocalNotification(message);
},
onLaunch: (Map<String, dynamic> message) async {
showToast("onLaunch Called : ${navigatorKey.currentState}", context);
print("onLaunch called : ${message.toString()}");
navigateToDetailScreen(message);
},
onResume: (Map<String, dynamic> message) async {
showToast("onResume Called : ${navigatorKey.currentState}", context);
print("onResume called : ${message.toString()}");
navigateToDetailScreen(message);
},
);
}
@override
void initState() {
super.initState();
setupFirebaseMessaging();
}
@override
Widget build(BuildContext context) {
_context = context;
return MaterialApp(
navigatorKey: navigatorKey,
debugShowCheckedModeBanner: false,
title: 'Test',
theme: ThemeData(
primaryColor: primaryColor,
accentColor: primaryDarkColor,
// visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SplashScreen(),
);
navigateToDetailScreen(Map<String, dynamic> message) async {
if (message['data']['id'] ==1) {
navigatorKey.currentState.pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginScreen()), (Route<dynamic> route) => false);
} else if (message['data']['id'] ==2) {
// some async work
navigatorKey.currentState.push(MaterialPageRoute(builder: (context) => DetailScreen()));
} else if (message['data']['id'] ==3) {
// some async work
navigatorKey.currentState.push(MaterialPageRoute(builder: (context) => DataScreen()));
} else {
// some async work
navigatorKey.currentState.push(MaterialPageRoute(builder: (context) => HomeScreen()));
}
}
Above code doesn't work for my case. I am not able to get navigated to my desired screen. Also, how to survive SplashScreen is your initialscreen when handling notification navigation with async calculation?
Can anyone suggest me a proper way to do so?
Thanks.