How to handle redirects from initState in Flutter
You can achieve this with the help of didNotificationLaunchApp
.
bool get didNotificationLaunchApp =>
notificationAppLaunchDetails?.didNotificationLaunchApp ?? false;
// Use here,
if (notificationAppLaunchDetails?.didNotificationLaunchApp ?? false) {
selectedNotificationPayload = notificationAppLaunchDetails!.payload;
initialRoute = SecondPage.routeName;
}
Pl check full example here : https://pub.dev/packages/flutter_local_notifications/example
For non main file :
@override
void initState() {
super.initState();
localNotification(); // call below localNotification() here.
}
localNotification() async {
final NotificationAppLaunchDetails? notificationAppLaunchDetails =
await flutterLocalNotificationsPlugin!.getNotificationAppLaunchDetails();
if (notificationAppLaunchDetails?.didNotificationLaunchApp ?? false) {
// redirect to new screen if true.
}
}

arriff
Updated on January 03, 2023Comments
-
arriff 12 minutes
I am using the plugin flutter_local_notifications to show a user notifications on the app. I have managed to show the notifications on the app and the user can click on the notifications, the user will be redirected to see all pending items from the notification in a notification page. I have set the function to detect the onclick on
initstate
. The whole function and method to show notification I have implemented it on the homescreen.@override void initState() { super.initState(); initPlatformState(); getNotifications(); NotificationApi.init(initScheduled: true); init(); _configureSelectNotificationSubject(); //function to redirect to Notifications page }
which goes to
void _configureSelectNotificationSubject() { print("clicked is the notification"); NotificationApi.onNotifications.stream.listen((String? payload) async { await Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => WANotifications(current: current)), (Route<dynamic> route) => true); }); }
The challenge am facing with this implementation is that when a user clicks to go to the home screen , the user gets redirected automatically to the notifications page from the home screen without his/her consent. The redirect should only occur when they click on the notifications.
How can I set the redirect to only occur when the user clicks the notification only and not when they click to go to home screen
-
John Joe 10 monthswhy you need to put it in initState?
-
arriff 10 monthsHi @JohnJoe from the plugin documentation you have to put it there otherwise it wont be called when you click the notification
-
John Joe 10 months
NotificationApi.onNotifications.stream
will only be called when there is a notification? -
arriff 10 months@JohnJoe yes that is correct
-
-
arriff 10 monthsthis is implemented on
main()
how can I use in a non main file? -
Jigar Fumakiya 10 monthswhy with a non-main file?
-
arriff 10 monthsbecause am implementing it in an initstate page, it is in the homepage of my app