Routing to Specific flutter Screen on click notification

Viewed 4664

How to go to specific screen on click notification? i used cloud function in javascript and when i click on the notification, it open me the app not the specific screen

 _fcm.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
    getOrder(message['data']['order_id']);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ListTile(
          title: Text(message['notification']['title']),
          subtitle: Text(message['notification']['body']),
        ),
        actions: <Widget>[
          FlatButton(
            child: Text('Ok'),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DetailOrder()));
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DetailOrder()));
  },
);
1 Answers

You could try to use named routes + global navigator key, it worked for me in a slightly different situation.
First setup a global navigator key like this:

...
class MyApp extends StatelessWidget {
  static final navigatorKey = GlobalKey<NavigatorState>();
  ...

Then right below define the named routes manager:

...
Route routes(RouteSettings settings) {
  if (settings.name == "/") {
    return MaterialPageRoute(
      builder: (_) => HomePage(),
    );
  } else if (settings.name.startsWith("/details/")) {
    try {
      String id = settings.name.split("/")[2];
      return MaterialPageRoute(
        builder: (_) => DetailPage(id),
      );
    } catch (e) {
      return MaterialPageRoute(
        builder: (_) => HomePage(),
      );
    }
  } else {
    return MaterialPageRoute(
      builder: (_) => HomePage(),
    );
  }
}
...

and add both the navigatorKey and the routes to the MaterialApp:

...
@override
Widget build(BuildContext context) {
  return MaterialApp(
    initialRoute: "/",
    onGenerateRoute: routes,
    title: 'MyApp',
    navigatorKey: navigatorKey,
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: HomePage(),
  );
}
...

After setting all this up you can navigate between your homepage and details using the navigator key like this:

MyApp.navigatorKey.currentState.pushNamed("/"); // to navigate to HomePage
MyApp.navigatorKey.currentState.pushNamed("/details/1"); // to navigate to DetailPage

Hope it works, good luck!

Related