如何解决GlobalKey<NavigatorState>().currentState.context 在推送时返回 null
我正在使用 Flutter 本地通知来管理本地通知。我希望当通知类型为“某些用户加入比赛”时,当通知用户点击通知时,他应该被带到比赛详细信息页面。最好的方法是使用 GlobalKey 作为 navigatorKey 并将其传递给 MaterialApp。但是我收到了这个错误。
(P.S.:此应用在 MainFrameApp() 中包含嵌套导航器,因此,在那里处理到 ContestDetailsPage 的进一步导航。)
我找不到原因,上下文为空。我认为使用 ChangeNotifier 的 setState 也可能导致了这个问题。所以我也提供了那个代码。
════════ Exception caught by widgets library ═══════════════════════════════════
The method 'push' was called on null.
Receiver: null
Tried calling: push<dynamic>(Instance of 'MaterialPageRoute<dynamic>')
The relevant error-causing widget was
MaterialApp
lib\main.dart:90
main.dart
import 'dart:convert';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:Flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_Flutter/hive_Flutter.dart';
import 'package:path_provider/path_provider.dart' as pathProvider;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sports_private_pool/models/authentication.dart';
import 'package:Flutter_local_notifications/Flutter_local_notifications.dart'
as local_notification;
import 'models/person.dart';
import 'screens/main_frame_app.dart';
import 'screens/welcome_screen.dart';
bool userLoggedIn = false;
SharedPreferences preferences;
local_notification.FlutterlocalnotificationsPlugin
FlutterlocalnotificationsPlugin =
local_notification.FlutterlocalnotificationsPlugin();
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
preferences = await SharedPreferences.getInstance();
final appDocumentDirectory =
await pathProvider.getApplicationDocumentsDirectory();
await Hive.initFlutter(appDocumentDirectory.path);
Hive.registeradapter(PersonAdapter());
await Hive.openBox<dynamic>('userData');
await Hive.openBox<Person>('user');
// Flutter Local Notification
var initializationSettingsAndroid =
local_notification.AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = local_notification.IOSInitializationSettings(
requestAlertPermission: true,requestBadgePermission: true,requestSoundPermission: true,onDidReceivelocalnotification:
(int id,String title,String body,String payload) async {},);
var initializationSettings = local_notification.InitializationSettings(
android: initializationSettingsAndroid,iOS: initializationSettingsIOS,);
FlutterlocalnotificationsPlugin.initialize(
initializationSettings,onSelectNotification: (String payload) async {
if (payload != null) {
try {
Map<String,dynamic> payloadJson = json.decode(payload);
if (payloadJson['data']['type'] == 'joinContest') {
Navigator.push(
navigatorKey.currentState.context,MaterialPageRoute(
builder: (context) => MainFrameApp(
defaultPage: 2,contestId: payloadJson['data']['contestId'],matchId: payloadJson['data']['matchId'],),);
}
} catch (e) {
print(e);
}
} else {
print("notification payload: $payload");
}
},);
runApp(
ChangeNotifierProvider(
create: (context) => Authentication(),child: MaterialApp(
title: 'Envision',navigatorKey: navigatorKey,theme: ThemeData(accentColor: Colors.black87),debugShowCheckedModeBanner: false,home: Envision(),);
}
class Envision extends StatefulWidget {
@override
_EnvisionState createState() => _EnvisionState();
}
class _EnvisionState extends State<Envision> {
Box<Person> userBox;
@override
initState() {
userBox = Hive.Box('user');
userLoggedIn = preferences.getString('email') != null;
print("EMAIL: ${preferences.getString('email')}");
Future.delayed(Duration.zero,() async {
if (userLoggedIn) {
Provider.of<Authentication>(context,listen: false)
.login(userBox.get('user'));
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<Authentication>(
builder: (context,state,child) {
if (state.loggedIn) {
return MainFrameApp();
}
return WelcomeScreen();
},);
}
}
身份验证.dart
import 'package:Flutter/foundation.dart';
import 'package:sports_private_pool/core/errors/exceptions.dart';
import 'package:sports_private_pool/models/person.dart';
class Authentication extends ChangeNotifier {
bool _loggedIn = false;
Person _user;
bool get loggedIn => _loggedIn;
Person get user => _loggedIn ? _user : throw NotFoundException();
void login(Person user) {
_loggedIn = true;
_user = user;
print("user logged in....");
notifyListeners();
}
void logout() {
_loggedIn = false;
print("user logged out...");
notifyListeners();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。