OneSignal / OneSignal-Flutter-SDK

OneSignal is a free push notification service for mobile apps. This plugin makes it easy to integrate your flutter app with OneSignal
https://www.onesignal.com
Other
625 stars 214 forks source link

Navigate to screen when notification is opened #58

Closed giacomomasseron closed 5 years ago

giacomomasseron commented 5 years ago

Description:

I need to navigate to a screen when the notification is opened, but I can't get it.
The app just is opened in main screen.

Environment onesignal: ^1.0.0

Steps to Reproduce Issue:

  1. Install the OneSignal Flutter SDK using pub into your project
  2. Initialize the SDK using OneSignal.shared.init(your_app_id)
  3. Attempt to receive a push notification

This is the code of my main.dart:

void main() async {
  // Create Persistor
  final persistor = Persistor<AppState>(
    storage: FlutterStorage(),
    serializer: JsonSerializer<AppState>(AppState.fromJson),
  );

  // Load initial state
  final initialState = await persistor.load();

  final store = Store<AppState>(
    appReducer, /* Function defined in the reducers file */
    initialState: initialState ?? AppState.initial(),
    middleware: [persistor.createMiddleware()],
  );

  OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);

  var settings = {
    OSiOSSettings.autoPrompt: false,
    OSiOSSettings.promptBeforeOpeningPushUrl: true
  };

  await OneSignal.shared.init("ID", iOSSettings: settings);

  OneSignal.shared.setInFocusDisplayType(OSNotificationDisplayType.notification);

  runApp(MyApp(store: store));
}

class MyApp extends StatefulWidget {
  final Store<AppState> store;

  const MyApp({Key key, this.store}) : super(key: key);

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    if (!mounted) return;

    OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => AnotherScreen(id: result.notification.payload.additionalData["id"]),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return new  StoreProvider<AppState>(
        store: widget.store,
        child: new MaterialApp(
            initialRoute: '/',
            theme: ThemeData(
              primaryColor: Color(0xff92171A),
              buttonTheme: ButtonThemeData(
                textTheme: ButtonTextTheme.accent,
              ),
            ),
            routes: {
              '/': (context) => HomeScreen(),
            }
        )
    );
  }
}

Anything else:

(crash stacktraces, as well as any other information here)

Nightsd01 commented 5 years ago

@GiacomoK Are you getting an error message...? Can you use a print statement to see if the NotificationOpenedHandler is actually being called?

There could be so many possible problems here, it's hard to help you without more details. I would test with the NotificationReceivedHandler first, it's easier to debug, so that you can make sure your UI logic actually works...

giacomomasseron commented 5 years ago

@Nightsd01 I tried with this code:

OneSignal.shared.setNotificationReceivedHandler((OSNotification notification) {
      print("setNotificationReceivedHandler");

      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => AnotherScreen(),
        ),
      );
    });

OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
  print("setNotificationOpenedHandler");
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => AnotherScreen(),
    ),
  );
});

And when I receive the notification I see "setNotificationReceivedHandler" on the log, but nothing else happens, the app (if its in foreground) remains on the same screen.

If I tap on the notification, I see "setNotificationOpenedHandler" on the log, but nothing else happens.

Nightsd01 commented 5 years ago

@GiacomoK that would mean this is an issue with how you are using Navigator.push(.... I would suggest debugging your UI code.

Since the opened handler is being called, this would not be a problem with our SDK.

When I have some time this weekend I will test your code but in the mean time if you figure out a solution please post it here as I’m sure other users will have a similar question

giacomomasseron commented 5 years ago

@Nightsd01 I use the same Navigator code in other part of the application and it works :(
I will try other things and let you know.

jkasten2 commented 5 years ago

@GiacomoK Closing due to inactivity. Feel free to reply if you are still seeing this issue.

flakerimi commented 5 years ago

Any update, facing same issue.

jkasten2 commented 5 years ago

@flakerimi This issue may be fixed in the latest 2.0.1 release. Can you follow the 2.0.0 migration guide and give it a try? https://github.com/OneSignal/OneSignal-Flutter-SDK/releases

Sonu7373 commented 5 years ago

still facing same issue unable to navigate when click on notification, any solution

harithany commented 5 years ago

Navigator.push not work . Any update, facing same issue.

garooo commented 5 years ago

You need to call .push() on the same Navigator object you istance in your MaterialApp.

https://stackoverflow.com/questions/52953985/how-do-i-open-a-specific-page-on-onesignal-notification-click-on-flutter

this worked fine for me.

harithany commented 5 years ago

You need to call .push() on the same Navigator object you istance in your MaterialApp.

https://stackoverflow.com/questions/52953985/how-do-i-open-a-specific-page-on-onesignal-notification-click-on-flutter

this worked fine for me.

Thanks it is work

jsonpreet commented 4 years ago

How to pass argument with route name?

vniroshan commented 1 year ago

{ "app_id": "YOUR_APP_ID", "included_segments": ["All"], "data": { "target": "specific_page", "page_id": "page_identifier" }, "contents": { "en": "Notification message" } }

SajidMasood commented 1 year ago

OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) { log("--------NotificationOpenedHandler---------"); var data = result.notification.additionalData; print(data); try { if (data != null) { // navigatorKey.currentState!.push(MaterialPageRoute( // builder: (context) => TestAds(postId: data["post_id"].toString()), // )); navigatorKey.currentState!.pushReplacement(MaterialPageRoute( builder: (context) => TestAds(postId: data["post_id"].toString()), )); } else { // navigate to another screen } } catch (e) { log(e.toString()); } });

ashishkaranwal commented 4 months ago

After struggling with the latest versions and trying all the suggested solutions, here's what worked for me:

Step 1: Define the Global Navigator Key

final GlobalKey navigatorKey = GlobalKey();

Step 2: Configure MaterialApp.router

MaterialApp.router( debugShowCheckedModeBanner: false, title: 'News Television', theme: darkTheme, darkTheme: darkTheme, routerConfig: router, );

Step 3: Navigate to the Desired Screen

navigatorKey.currentState?.push( MaterialPageRoute( builder: (context) => NewsReadScreen( id: data['post_id'].toString(), title: data['Title'], content: data['Content'] ?? '', date: data['Date'], pagePath: data['post_link'], image: data['post_image'], ), ), );

These setups resolved my issues with navigation in the latest versions.

nithaparveen commented 4 months ago

This is what worked for me

CODE :

class MyApp extends StatelessWidget { const MyApp({super.key});

static final navigatorKey = GlobalKey();

@override Widget build(BuildContext context) { int? lead_id; OneSignal.Notifications.addClickListener((event) { final data = event.notification.additionalData; lead_id = data?['lead_id']; if (lead_id != null) { navigatorKey.currentState?.push( MaterialPageRoute( builder: (context) => LeadDetailScreen( leadId: lead_id, ), ), ); } log(" DATA =====> $lead_id"); }); return MaterialApp( navigatorKey: navigatorKey, theme: ThemeData(appBarTheme: const AppBarTheme(color: Colors.white)), debugShowCheckedModeBanner: false, home: const LoginScreen(), ); } }

POST : https://api.onesignal.com/notifications

{ "app_id": "APP ID", "contents": { "en": "New Lead Alert" }, "data":{ "lead_id": 18294 }, "target_channel": "push", "include_subscription_ids": [ "SUBSCRIPTION ID" ] }