我想在用户点击 fcm
通知时导航特定页面。问题是导航器不适用于回调方法。
- 我的设备很好地收到了推送通知。
- 我在通知正文中添加了
FLUTTER_NOTIFICATION_CLICK
。并且没有丢失数据。 - 回调方法运行良好,但只有
Navigator
和showDialog
不起作用。所以我猜问题与context
有关。
// main.dart
void main() {
SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _AppState();
}
class _AppState extends State<MyApp> {
final FirebaseMessaging _fm = new FirebaseMessaging();
final GlobalKey<NavigatorState> navigatorKey =
GlobalKey(debugLabel: 'Main Navigator');
final routes = {
// skip on question
};
fcmSetting(context) {
_fm.configure(
onLaunch: (Map<String, dynamic> message) {
pushTo(message); // not work
},
onMessage: (Map<String, dynamic> message) {
print('onMessage $message'); // it run well
onMessageSend(message); // but it's not
},
onResume: (Map<String, dynamic> message) {
pushTo(message); // not work
},
);
_fm.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true));
_fm.getToken().then((token) {
DBFactory.getInstance().insert('fcmToken', token);
});
}
pushTo(message) {
if (message['type'] == 'notice') {
Navigator.of(navigatorKey.currentContext).push(
MaterialPageRoute(builder: (_) => NoticeDetailScreen(message['id'])));
}
}
onMessageSend(message) {
showDialog(
context: context,
builder: (bd) => new AlertDialog(
title: LText('메세지 도착!'),
content: LText('$message'),
actions: <Widget>[
LFlatButton(
text: '확인', onPressed: () => Navigator.of(bd).pop()),
],
));
}
@override
Widget build(BuildContext context) {
fcmSetting(context);
return new MaterialApp(
navigatorKey: navigatorKey,
title: 'App title',
initialRoute: '/',
routes: routes,
);
}
}
我已经尝试过 Navigator.of(navigat
Navigator.of(navigatorKey.currentContext).push(...)orKey.currentContext).push(...)
或 Navigator.of(context).push(...)
。但不起作用。
如何解决?
最佳答案
您必须将代码从 App 文件移动到小部件中。我会说创建一个主页并在其中执行导航,使主页成为您的 MaterialApp 的子页面并在主页 View 中注册回调。
我还没有弄清楚为什么那里的上下文不起作用,但我最近遇到了同样的事情,不得不将导航移动到更深层次的 View 中。
关于dart - 导航器在 Firebase 消息回调方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740695/