arriff
arriff

Reputation: 439

How to handle redirects from initState in Flutter

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

Upvotes: 2

Views: 754

Answers (1)

Yashraj
Yashraj

Reputation: 999

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. 
    }
  }

Upvotes: 3

Related Questions