导航不稳定,请重新打开页面,而不是再次推送页面 [英] Flutter navigation, reopen page instead of pushing it again
问题描述
我是新手,正在开发具有多个屏幕的应用程序.
I'm new to flutter and I'm working on an App that have multiple screens.
我想知道不要因为创建同一路线的多个屏幕而停止颤动,例如,我有第1页和第2页,如果我单击该按钮导航到第2页,然后再次单击同一按钮,则应用程序将按第2页,我将获得两次,如果单击返回按钮,它将把我带回到第一个创建的第2页
I would like to know to stop flutter from creating multiple screens of the same route, for example I have Page 1 and Page 2, if I click on the button to navigate to Page 2 and clicked again on the same button the application will push a new screen of Page 2 and i will have it twice and if I click on the return button it will send me back to the first created Page 2
是否有一种方法可以只创建一次每个页面,然后在已经将其推入堆栈时重新打开它?
is there a way to create every page only once and then reopen it if it's already pushed to the stack ?
我正在使用 Navigator.push
进行所有导航
I'm using Navigator.push
for all my navigation
推荐答案
在此处使用简单的逻辑
-
如果新页面与当前页面相同,则使用
Navigator.push(context,route)
.
如果新页面不同,则使用 Navigator.pushReplacement(context,route)
.
If the new page is the different then use Navigator.pushReplacement(context,route)
.
如果您使用的是命名路由,则用于
In case if you are using named routes then for
- 与当前页面相同,使用
Navigator.pushNamed(context,name)
. - 不同页面,使用
Navigator.pushReplacementNamed(context,name)
.
完整的代码示例
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SO(),
);
}
}
class SO extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageOne(),
);
}
}
class PageOne extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page 1'),
),
backgroundColor: Colors.amber,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RaisedButton(
onPressed: () {
print('creating replacement page 1');
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) {
return PageOne();
}));
},
child: Text('Go to page 1'),
),
RaisedButton(
onPressed: () {
print('creating new page 2');
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
return PageTwo();
}));
},
child: Text('Go to page 2'),
),
],
),
),
);
}
}
class PageTwo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page 2'),
),
backgroundColor: Colors.brown,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RaisedButton(
onPressed: () {
print('creating new page 1');
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => PageOne()));
},
child: Text('Go to page 1'),
),
RaisedButton(
onPressed: () {
print('creating replacement page 2');
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => PageTwo()));
},
child: Text('Go to page 2'),
),
],
),
),
);
}
}
这篇关于导航不稳定,请重新打开页面,而不是再次推送页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!