我找到了解决方案。这是给我带来问题的代码:
class Login extends StatelessWidget
{
void homePage(BuildContext context)
{
Navigator.pushNamed(context, "/my_home");
}
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Login"),
),
body: Center(
child:
Column(
children: [
Text("Welcome to the Login Page"),
ElevatedButton(
onPressed: ()
{
homePage(context);
},
child: Text("Login"),
),
],
)
),
);
}
}
class MyHome extends StatelessWidget
{
void removePreviousRoutes(BuildContext context)
{
//The problem code.
Navigator.of(context).pushNamedAndRemoveUntil('/my_home', (Route<dynamic> route) => false);
}
Widget build(BuildContext context)
{
WidgetsBinding.instance.addPostFrameCallback((_) => removePreviousRoutes(context));
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("My Home"),
),
body: Center(
child:
Text("Welcome to the Home Page"),
)
);
}
}
将显示的初始页面是登录。在用户点击“欢迎来到登录页面”后,他们将被引导至 MyHome 页面。问题来自 MyHome 页面上的 Navigator.of(context).pushNamedAndRemoveUntil('/my_home', (Route<dynamic> route) => false);。
解决方案:
class Login extends StatelessWidget
{
void homePage(BuildContext context)
{
//The solution.
Navigator.pushNamed(context, "/my_home");
Navigator.of(context).pushNamedAndRemoveUntil('/my_home', (Route<dynamic> route) => false);
}
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Login"),
),
body: Center(
child:
Column(
children: [
Text("Welcome to the Login Page"),
ElevatedButton(
onPressed: ()
{
homePage(context);
},
child: Text("Login"),
),
],
)
),
);
}
}
class MyHome extends StatelessWidget
{
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("My Home"),
),
body: Center(
child:
Text("Welcome to the Home Page"),
)
);
}
}
解决方案是推送新路由并从登录中删除所有以前的路由,INSTEAD OF在中推送新路由登录并从注册中删除以前的路线。完成此操作后,我不再收到闪烁的问题。