【发布时间】:2019-01-10 21:50:52
【问题描述】:
我正在使用本地通知插件,一切正常,除了当我点击通知时。我想在用户点击通知时导航到特定屏幕
Future onSelectNotification(String payload) async {
//convert payload json to notification model object
try{
Map notificationModelMap = jsonDecode(payload);
NotificationModel model = NotificationModel.fromJson(notificationModelMap);
await Navigator.push(
context,// it`s null!
new MaterialPageRoute(
builder: (context) => CommitmentPage(model)));}
catch(e){print(e.toString());}
}
但上下文始终为空并给我一个例外
NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
编辑
我尝试按照@Günter Zöchbauer 的建议使用 navigatorKey 并将其传递给材料应用程序,但它给了我另一个例外
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget
main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static final navigatorKey = new GlobalKey<NavigatorState>();
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
navigatorKey:navigatorKey ,
title: 'notification',
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: new RootPage(auth: new Auth(),),
);
}
}
提醒页面
class ReminderPage extends StatefulWidget {
@override
_ReminderPageState createState() => _ReminderPageState();
}
class _ReminderPageState extends State<ReminderPage> {
final flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
....
@override
void initState() {
super.initState();
_initLocalNotification();
....
}
// this method is called when u tap on the notification
Future onSelectNotification(String payload) async {
//convert payload json to notification model object
Map notificationModelMap = jsonDecode(payload);
NotificationModel model = NotificationModel.fromJson(notificationModelMap);
try{
await Navigator.push(
MyApp.navigatorKey.currentState.context,
new MaterialPageRoute(
builder: (context) => CommitmentPage(model)));}
catch(e){print(e.toString());}
}
}
编辑 2 而不是使用
await Navigator.push(
MyApp.navigatorKey.currentState.context,
new MaterialPageRoute(
builder: (context) => CommitmentPage(model)));}
catch(e){print(e.toString());}
我用过
await MyApp.navigatorKey.currentState.push(MaterialPageRoute(builder: (context) => CommitmentPage(model)));
它运行良好,但是当我在终止应用程序后点击通知时,它会将我带到主页而不是所需的主页! 我认为 navigatorKey 还没有初始化!
【问题讨论】:
-
你能再分享一些代码吗?你怎么称呼你的通知?
标签: dart flutter flutter-layout