Navigating through screens in an app is a very important feature as apps contain two or more screens. This is because a screen would contain a different content from another another screen. In flutter a screen is called a route.
To achieve this, creating the two routes is the first step. Page1 and page2 will be the name of the routes respectively
Each of this routes have a button that would allow the navigation to be possible when they are clicked.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: const Text('First page'),
),
body: Center(
child: ElevatedButton(
child: Text("Next page"),
onPressed: (){
Navigator.push(context,MaterialPageRoute(builder: (context)=> const page2()));
},
),
),
),
);
}
}
class page2 extends StatelessWidget {
const page2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea (
child: Scaffold(
appBar: AppBar(
title: const Text('Page 2'),
),
body: Center(
child: ElevatedButton(
child: Text('Go back'),
onPressed: (){
Navigator.pop(context);
},
),
),
),
);
}
}
Switching to a new route(page) requires the navigator.push() method. This method is updated in the onPressed callback or our button of the first page. This will enable us to to navigate to the next route page2
body: Center(
child: ElevatedButton(
child: Text("Next page"),
onPressed: (){
Navigator.push(context,MaterialPageRoute(builder: (context)=> const page2()));
},
),
),
Now to go back to the first page the onpressed callback of the button here is filled Navigator.pop(context)
body: Center(
child: ElevatedButton(
child: Text('Go back'),
onPressed: (){
Navigator.pop(context);
},
),
)
Below shows the output of the first page which is also the homepage and the second page:
I woud be using this technique to navigate through pages till I figure out a new and better technique on my learning process. I have uploaded the code to my github profile.
Please let me know what you think about it.