错误:
使用不包含导航器的上下文请求导航器操作。 用于从导航器推送或弹出路由的上下文必须是导航器小部件的后代小部件的上下文。
逻辑如下: 如果用户是新用户,第一次运行应用程序,加载屏幕,闪屏,每日一次的肯定,这是一个固定的肯定,不能改变(“在隆冬,我发现我体内有一个无敌的夏天。” )然后是初始屏幕。 如果用户注册并登录,运行应用程序应显示加载屏幕、启动屏幕、从 firestore 确认中随机提取的每日确认,然后显示主屏幕。
enter code here
// Show flow for logged-in users
void _showAffirmationsAndNavigate() {
print('Starting _showAffirmationsAndNavigate...');
// Ensure the user state is correct
if (currentUser == null) {
print('Error: currentUser is null during navigation.');
} else {
print('User is logged in with UID: ${currentUser!.uid}');
}
// Ensure the right context for navigation
WidgetsBinding.instance.addPostFrameCallback((_) {
Builder(builder: (BuildContext context) {
if (currentUser != null) {
print('Navigating to HomeView...');
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomeView(
userId: currentUser!.uid,
affirmationService: affirmationService,
),
),
);
} else {
print('Navigating to InitialScreen for non-logged-in users...');
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const InitialScreen(),
),
);
}
return Container(); // Dummy return, as Builder requires a widget to return
});
});
} ''' '''
发生错误的原因是所使用的上下文未链接到正确的导航器。在 postFrameCallback 中使用构建器可能会导致上下文未连接到导航器小部件。
解决方案 确保调用 _showAffirmationsAndNavigate 时直接传递正确的上下文,或使用 Navigator.of(context, rootNavigator: true) 访问根导航器。
重构代码:
void _showAffirmationsAndNavigate(BuildContext context) {
print('Starting _showAffirmationsAndNavigate...');
if (currentUser == null) {
print('Error: currentUser is null during navigation.');
} else {
print('User is logged in with UID: ${currentUser!.uid}');
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (currentUser != null) {
print('Navigating to HomeView...');
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomeView(
userId: currentUser!.uid,
affirmationService: affirmationService,
),
),
);
} else {
print('Navigating to InitialScreen for non-logged-in users...');
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const InitialScreen(),
),
);
}
});
}