我试图在我的应用程序中实现的是,当用户收到推送通知时,应用程序将推送一个新的小部件。我正确获得了通知数据,但无法使其工作。
这是通知的侦听器
_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
时,将密钥传递给它
child: MaterialApp(
navigatorKey: navigatorKey,
在您的应用程序中,您现在可以使用navigatorKey.currentState.push()
等