我试图在我的应用程序中实现的是,当用户收到推送通知时,应用程序将推送一个新的小部件。我正确地获取了通知数据,但无法使其正常工作。
这是通知的监听器
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
_manageNotificationData(message);
},
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
_manageNotificationData(message);
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
_manageNotificationData(message);
},
);
我的负载是
data: {
"id" : "Id for notification state",
"click_action": "FLUTTER_NOTIFICATION_CLICK","
"orderId": "SomeId"
}
void _manageNotificationData(Map<String,dynamic> message){
//When the user receives a notification, a new widget will appear so that he can rate another user
if(message["id"] == 1){
//This data is printed in the console
print(message["orderId"]);
//this is not working
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>
RateProfessionalWidget(
orderId: message["orderId"])
),
);
}
}
我猜这是行不通的,因为我在主文件中调用了 Navigator.push,但在这个文件中是我唯一可以访问通知数据的地方。我怎样才能完成这项工作?
最佳答案
确保您的应用(您runApp()
)是一个StatefulWidget
,并在其状态下创建一个GlobalKey
GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'navKey');
当您创建 MaterialApp
时,将 key 传递给它
child: MaterialApp(
navigatorKey: navigatorKey,
在您的应用中,您现在可以使用 navigatorKey.currentState.push()
等
关于push-notification - 如何在收到远程通知时推送导航到新的 Widget?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819478/