Flutter本地通知onSelectNotification点击本地通知时无法打开新页面

Haf*_*kib 9 android ios dart flutter

我希望我的 flutter 应用程序在单击本地通知时打开一个页面。我在事件监听器中定义了以下代码:

Navigator.push(
   Ccontext,
   MaterialPageRoute(builder: (context) => PendingOrders()),
 );
debugPrint('notification payload: ' + payload);
Run Code Online (Sandbox Code Playgroud)

当调用本地通知时,事件监听器执行成功并打印debugPrint的参数,但无法打开PendingOrders路由。

这是 main.dart 中的完整代码

  class _MyAppState extends State<MyApp> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
@override
void initState() {
  super.initState();

  var android = AndroidInitializationSettings('mipmap/ic_launcher');
  var ios =  IOSInitializationSettings();
  var platform = InitializationSettings(android, ios);
  flutterLocalNotificationsPlugin.initialize(platform,onSelectNotification: onSelectNotification);

  _firebaseMessaging.subscribeToTopic('order-created');
  _firebaseMessaging.configure(
    onMessage: (Map<String, dynamic> message) async {
      print("onMessage: $message");
      showNotification(message);
    },
    onLaunch: (Map<String, dynamic> message) async {
      print("onLaunch: $message");
      print("Hafijur");
    },
    onResume: (Map<String, dynamic> message) async {
      print("onResume: ${message['notification']['data']['click_action']}");
    },
  );
  _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true));
}

showNotification(Map<String, dynamic> msg) async {
  var android = new AndroidNotificationDetails(
    'sdffds dsffds',
    "CHANNLE NAME",
    "channelDescription",
  );
  var iOS = new IOSNotificationDetails();
  var platform = new NotificationDetails(android, iOS);
  await flutterLocalNotificationsPlugin.show(
      0, "New order arrived", "Hey, hurry up! you have a order to deliver", platform,payload: "order created");
}
 Future onSelectNotification(String payload) async {
  this.build(context);
   Navigator.push(
     context,
     MaterialPageRoute(builder: (context) => PendingOrders()),
   );
   if (payload != null) {
    debugPrint('notification payload: ' + payload);
  }
}

@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Demo',
    theme: Constants.lightTheme,
    debugShowCheckedModeBanner: false,
    routes: {
      "/": (context) => MainScreen(),
      "/login": (context) => LoginPage(),
      "/dashboard": (context) => Dashboard(),
      "/all_orders": (context) => AllOrders(),
      "/pending_orders": (context) => PendingOrders(),
      "/delivered_orders": (context) => DeliveredOrders(),
      "/order": (context) => Order(),
    },
  );
}
}
Run Code Online (Sandbox Code Playgroud)

Ran*_*ani 19

要在应用程序通过点击通知打开后关闭时接收有效负载,您必须使用getNotificationAppLaunchDetails方法

final NotificationAppLaunchDetails? notificationAppLaunchDetails =
await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
String? payload = notificationAppLaunchDetails!.payload;
Run Code Online (Sandbox Code Playgroud)

将此代码放在通知初始化行之后的 main 中

仅当点击通知时应用程序已打开时,才会触发onSelectNotification

但如果应用程序已经关闭,并且您想在点击通知并处理有效负载值后运行它,那么您必须使用getNotificationAppLaunchDetails

代码如下:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  var initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');
  var initializationSettingsIOs = IOSInitializationSettings();
  var initSetttings = InitializationSettings(
      android: initializationSettingsAndroid, iOS: initializationSettingsIOs);
  var cnf = await flutterLocalNotificationsPlugin.initialize(initSetttings,
      onSelectNotification: onSelectNotification);
  final NotificationAppLaunchDetails? notificationAppLaunchDetails =
      await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();

  print('payload=');
  String? payload= notificationAppLaunchDetails!.payload;
  print(payload);

    runApp(
         MaterialApp(        
          home: payload== 'page1' ? Page1() : MainPage()
         )
       ); 
}
Run Code Online (Sandbox Code Playgroud)


小智 10

flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();\nvar initializationSettingsAndroid =\n          const AndroidInitializationSettings('@drawable/icon_menu_car_no');\n      var initializationSettingsIOs = const IOSInitializationSettings();\n      var initSettings = InitializationSettings(\n          android: initializationSettingsAndroid,\n          iOS: initializationSettingsIOs);\n      flutterLocalNotificationsPlugin?.initialize(initSettings,\n          onSelectNotification: (payload) {\n           switch(payload){\n               case "A":\n                 //route  to some where \n                break;\n\n           }\n      });\n\nFirebaseMessaging.onMessage.listen((message) async {\n       showNotification(message);\n});\n
Run Code Online (Sandbox Code Playgroud)\n
void showNotification(RemoteMessage message) {\n    RemoteNotification? notification = message.notification;\n    AndroidNotification? android = message.notification?.android;\n    if (notification != null && android != null && !kIsWeb) {\n      var messageData = FirebaseMessageObject.fromJson(message.data);\n      flutterLocalNotificationsPlugin?.show(\n          notification.hashCode,\n          notification.title,\n          notification.body,\n          NotificationDetails(\n            android: AndroidNotificationDetails(\n              channel!.id,\n              channel!.name,\n              channelDescription: channel!.description,\n              icon: 'icon_menu_car_no',\n            ),\n          ),\n          payload: messageData.functionID);\n    }\n  }\n
Run Code Online (Sandbox Code Playgroud)\n
class FirebaseMessageObject{\n  late String functionID;\n\n  static FirebaseMessageObject fromJson(Map<String,dynamic> data){\n    FirebaseMessageObject object =  FirebaseMessageObject();\n    object.functionID = data['functionID'];\n    return object;\n  }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x80\xbbFCM 请求

\n
{\n    "to": "your fcm token ",\n    "notification": {\n         "body": "I am body ",\n         "title": "I am title ",\n         "sound": "default"\n    },\n    "data":{\n            "functionID":"A"\n    },\n    "priority": "high"\n}\n
Run Code Online (Sandbox Code Playgroud)\n