I'm new to flutter and I'm working on an App that have multiple screens.
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 ?
I'm using Navigator.push
for all my navigation
Using a simple logic here
If the new page is the same as the current page then use Navigator.push(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)
.Complete code sample
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'),
),
],
),
),
);
}
}