Flutter Navigation and Routing

 

Flutter Navigation and Routing

Navigation and routing are some of the core concepts of all mobile application, which allows the user to move between different pages. We know that every mobile application contains several screens for displaying different types of information. For example, an app can have a screen that contains various products. When the user taps on that product, immediately it will display detailed information about that product.

In Flutter, the screens and pages are known as routes, and these routes are just a widget. In Android, a route is similar to an Activity, whereas, in iOS, it is equivalent to a ViewController.

In any mobile app, navigating to different pages defines the workflow of the application, and the way to handle the navigation is known as routing. Flutter provides a basic routing class MaterialPageRoute and two methods Navigator.push() and Navigator.pop() that shows how to navigate between two routes. The following steps are required to start navigation in your application.

Step 1: First, you need to create two routes.

Step 2: Then, navigate to one route from another route by using the Navigator.push() method.

Step 3: Finally, navigate to the first route by using the Navigator.pop() method.

Let us take a simple example to understand the navigation between two routes:

Create two routes

Here, we are going to create two routes for navigation. In both routes, we have created only a single button. When we tap the button on the first page, it will navigate to the second page. Again, when we tap the button on the second page, it will return to the first page. The below code snippet creates two routes in the Flutter application.

  1. class FirstRoute extends StatelessWidget {  
  2.   @override  
  3.   Widget build(BuildContext context) {  
  4.     return Scaffold(  
  5.       appBar: AppBar(  
  6.         title: Text('First Route'),  
  7.       ),  
  8.       body: Center(  
  9.         child: RaisedButton(  
  10.           child: Text('Open route'),  
  11.           onPressed: () {  
  12.             // Navigate to second route when tapped.  
  13.           },  
  14.         ),  
  15.       ),  
  16.     );  
  17.   }  
  18. }  
  19.   
  20. class SecondRoute extends StatelessWidget {  
  21.   @override  
  22.   Widget build(BuildContext context) {  
  23.     return Scaffold(  
  24.       appBar: AppBar(  
  25.         title: Text("Second Route"),  
  26.       ),  
  27.       body: Center(  
  28.         child: RaisedButton(  
  29.           onPressed: () {  
  30.             // Navigate back to first route when tapped.  
  31.           },  
  32.           child: Text('Go back!'),  
  33.         ),  
  34.       ),  
  35.     );  
  36.   }  
  37. }  

Navigate to the second route using Navigator.push() method

The Navigator.push() method is used to navigate/switch to a new route/page/screen. Here, the push() method adds a page/route on the stack and then manage it by using the Navigator. Again we use MaterialPageRoute class that allows transition between the routes using a platform-specific animation. The below code explain the use of the Navigator.push() method.

  1. // Within the `FirstRoute` widget  
  2. onPressed: () {  
  3.   Navigator.push(  
  4.     context,  
  5.     MaterialPageRoute(builder: (context) => SecondRoute()),  
  6.   );  
  7. }  

Return to the first route using Navigator.pop() method

Now, we need to use Navigator.pop() method to close the second route and return to the first route. The pop() method allows us to remove the current route from the stack, which is managed by the Navigator.

To implement a return to the original route, we need to update the onPressed() callback method in the SecondRoute widget as below code snippet:

  1. // Within the SecondRoute widget  
  2. onPressed: () {  
  3.   Navigator.pop(context);  
  4. }  

Now, let us see the full code to implement the navigation between two routes. First, create a Flutter project and insert the following code in the main.dart file.

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() {  
  4.   runApp(MaterialApp(  
  5.     title: 'Flutter Navigation',  
  6.     theme: ThemeData(  
  7.       // This is the theme of your application.  
  8.       primarySwatch: Colors.green,  
  9.     ),  
  10.     home: FirstRoute(),  
  11.   ));  
  12. }  
  13.   
  14. class FirstRoute extends StatelessWidget {  
  15.   @override  
  16.   Widget build(BuildContext context) {  
  17.     return Scaffold(  
  18.       appBar: AppBar(  
  19.         title: Text('First Screen'),  
  20.       ),  
  21.       body: Center(  
  22.         child: RaisedButton(  
  23.           child: Text('Click Here'),  
  24.           color: Colors.orangeAccent,  
  25.           onPressed: () {  
  26.             Navigator.push(  
  27.               context,  
  28.               MaterialPageRoute(builder: (context) => SecondRoute()),  
  29.             );  
  30.           },  
  31.         ),  
  32.       ),  
  33.     );  
  34.   }  
  35. }  
  36.   
  37. class SecondRoute extends StatelessWidget {  
  38.   @override  
  39.   Widget build(BuildContext context) {  
  40.     return Scaffold(  
  41.       appBar: AppBar(  
  42.         title: Text("Second Screen"),  
  43.       ),  
  44.       body: Center(  
  45.         child: RaisedButton(  
  46.           color: Colors.blueGrey,  
  47.           onPressed: () {  
  48.             Navigator.pop(context);  
  49.           },  
  50.           child: Text('Go back'),  
  51.         ),  
  52.       ),  
  53.     );  
  54.   }  
  55. }  

Output

When you run the project in the Android Studio, you will get the following screen in your emulator. It is the first screen that contains only a single button.

Flutter Navigation and Routing

Click the button Click Here, and you will navigate to a second screen as below image. Next, when you click on the button Go Back, you will return to the first page.

Flutter Navigation and Routing

Navigation with Named Routes

We have learned how to navigate to a new screen by creating a new route and manage it by using the Navigator. The Navigator maintains the stack-based history of routes. If there is a need to navigate to the same screen in many parts of the app, this approach is not beneficial because it results in code duplication. The solution to this problem can be removed by defining the named routes and can use the named routes for navigation.

We can work with named routes by using the Navigator.pushNamed() function. This function takes two required arguments (build context and string) and one optional argument. Also, we know about the MaterialPageRoute, which is responsible for page transition. If we do not use this, then it is difficult to change the page.

The following steps are necessary, which demonstrate how to use named routes.

Step 1: First, we need to create two screens. The following code creates the two screens in our app.

  1. class HomeScreen extends StatelessWidget {  
  2.   @override  
  3.   Widget build(BuildContext context) {  
  4.     return Scaffold(  
  5.       appBar: AppBar(  
  6.         title: Text('Home Screen'),  
  7.       ),  
  8.       body: Center(  
  9.         child: RaisedButton(  
  10.           child: Text('Click Here'),  
  11.           color: Colors.orangeAccent,  
  12.           onPressed: () {  
  13.             //  
  14.           },  
  15.         ),  
  16.       ),  
  17.     );  
  18.   }  
  19. }  
  20.   
  21. class SecondScreen extends StatelessWidget {  
  22.   @override  
  23.   Widget build(BuildContext context) {  
  24.     return Scaffold(  
  25.       appBar: AppBar(  
  26.         title: Text("Second Screen"),  
  27.       ),  
  28.       body: Center(  
  29.         child: RaisedButton(  
  30.           color: Colors.blueGrey,  
  31.           onPressed: () {  
  32.             //  
  33.           },  
  34.           child: Text('Go back!'),  
  35.         ),  
  36.       ),  
  37.     );  
  38.   }  
  39. }  

Step 2: Define the routes.

In this step, we have to define the routes. The MaterialApp constructor is responsible for defining the initial route and other routes themselves. Here the initial route tells the start of the page and routes property defines the available named routes and widgets. The following code explains it more clearly.

  1. MaterialApp(  
  2.   title: 'Named Route Navigation',  
  3.   theme: ThemeData(  
  4.     // This is the theme of your application.  
  5.     primarySwatch: Colors.green,  
  6.   ),  
  7.   // It start the app with the "/" named route. In this case, the app starts  
  8.   // on the HomeScreen widget.  
  9.   initialRoute: '/',  
  10.   routes: {  
  11.     // When navigating to the "/" route, build the HomeScreen widget.  
  12.     '/': (context) => HomeScreen(),  
  13.     // When navigating to the "/second" route, build the SecondScreen widget.  
  14.     '/second': (context) => SecondScreen(),  
  15.   },  
  16. ));  

Step 3: Navigate to the second screen using the Navigator.pushNamed() function.

In this step, we need to call Navigator.pushNamed() method for navigation. For this, we need to update an onPressed() callback in the build method of HomeScreen like below code snippets.

  1. onPressed: () {  
  2.   // Navigate to the second screen by using the named route.  
  3.   Navigator.pushNamed(context, '/second');  
  4. }  

Step 4: Use a Navigator.pop() function to return to the first screen.

It is the final step, where we will use Navigator.pop() method to return on the first screen.

  1. onPressed: () {  
  2.   Navigator.pushNamed(context, '/second');  
  3. },  

Let us see the full code of the above explanation in the Flutter project and run it in the emulator to get the output.

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() {  
  4.   runApp( MaterialApp(  
  5.     title: 'Named Route Navigation',  
  6.     theme: ThemeData(  
  7.       // This is the theme of your application.  
  8.       primarySwatch: Colors.green,  
  9.     ),  
  10.     // Start the app with the "/" named route. In this case, the app starts  
  11.     // on the FirstScreen widget.  
  12.     initialRoute: '/',  
  13.     routes: {  
  14.       // When navigating to the "/" route, build the FirstScreen widget.  
  15.       '/': (context) => HomeScreen(),  
  16.       // When navigating to the "/second" route, build the SecondScreen widget.  
  17.       '/second': (context) => SecondScreen(),  
  18.     },  
  19.   ));  
  20. }  
  21.   
  22. class HomeScreen extends StatelessWidget {  
  23.   @override  
  24.   Widget build(BuildContext context) {  
  25.     return Scaffold(  
  26.       appBar: AppBar(  
  27.         title: Text('Home Screen'),  
  28.       ),  
  29.       body: Center(  
  30.         child: RaisedButton(  
  31.           child: Text('Click Here'),  
  32.           color: Colors.orangeAccent,  
  33.           onPressed: () {  
  34.             Navigator.pushNamed(context, '/second');  
  35.           },  
  36.         ),  
  37.       ),  
  38.     );  
  39.   }  
  40. }  
  41.   
  42. class SecondScreen extends StatelessWidget {  
  43.   @override  
  44.   Widget build(BuildContext context) {  
  45.     return Scaffold(  
  46.       appBar: AppBar(  
  47.         title: Text("Second Screen"),  
  48.       ),  
  49.       body: Center(  
  50.         child: RaisedButton(  
  51.           color: Colors.blueGrey,  
  52.           onPressed: () {  
  53.             Navigator.pop(context);  
  54.           },  
  55.           child: Text('Go back!'),  
  56.         ),  
  57.       ),  
  58.     );  
  59.   }  
  60. }  

Output

Flutter Navigation and Routing

Click the button Click Here, and you will navigate to a second screen as below image. Next, when you click on the button Go Back, it will return to the Home Page.

Flutter Navigation and Routing


Post a Comment

Previous Post Next Post