这个问题是在android项目中遇到的。
当我在 screen3 处按后退按钮时,第一次按下的按钮将被忽略,第二次按下的按钮会将我带到 screen1。
从后退按钮的响应中可以明显看出,堆栈中有一个空槽。如果我在 Navigator.pushReplacement 之后调用 Navigator.pop,问题就会得到解决,但在显示 screen3 之前它会暂时转到 screen1。
这是我从 screen1(主屏幕)到达 screen2(通知)的代码
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Notifications())
);
},
从 screen2 转到 screen3 的代码
void moveToUserYscreen({
required BuildContext context,
required Contact contactY,
bool replace = false,
}) {
int initialTabIndex = 0;
if (contactY.interacted != null && contactY.interacted!) {
// Set initialTabIndex
initialTabIndex = 1;
}
// Register activeUid in the CloudData object
CloudData.activeUid = contactY.uid;
if (replace) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => UserYscreen(
contactY: contactY,
initialTabIndex: initialTabIndex,
),
),
);
// Navigator.pop(context);
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserYscreen(
contactY: contactY,
initialTabIndex: initialTabIndex,
),
),
);
}
我觉得你的逻辑有点问题
在此特定代码中,您缺少“return”语句,这就是您的第一次后退单击被忽略的原因。如果replace为true,那么在执行pushReplacement之后,你必须返回/中断这个函数的流程。
if (replace) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => UserYscreen(
contactY: contactY,
initialTabIndex: initialTabIndex,
),
),
);
// Navigator.pop(context);
return ; //<<ADD THIS
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserYscreen(
contactY: contactY,
initialTabIndex: initialTabIndex,
),
),
);
}