Flutter Navigation Between Two Pages
In this tutorial, we will learn how to navigate between two screens.
We shall learn two steps in navigation. They are:
- Loading second screen from first screen.
- Returning to first screen from second screen.
To load a new screen, we can use Navigator.push() and to return back to the previous screen, we can use Navigator.pop().
Example
In this example, we have two screens/pages, they are: MyHomePage and MySecondPage which extend StatefulWidget. They both have different state classes.
In MyHomePage, we shall place a button and when this button is pressed, we shall navigate to second screen, MySecondPage.
In MySecondPage, we shall place a RaisedButton and when this button is pressed, we shall navigate back to the first screen MyHomePage.
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class MySecondPage extends StatefulWidget {
@override
_MySecondPageState createState() => _MySecondPageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home - TutorialKart'),
),
body: Center(
child: RaisedButton(
child: Text('Go to Second Screen'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MySecondPage()),
);
},
),
),
);
}
}
class _MySecondPageState extends State<MySecondPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Go back to Home Screen'),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
Run this application and you should get the first and second screen as shown below.
Complete Project
You can find the complete code at – Github – TutorialKart – Flutter – Navigation Example.
Conclusion
In this Flutter Tutorial, we learned how to navigate between two screens/pages using Navigator.push() and Navigator.pop().