How do you use navigation and routing in Flutter?

Hey Everyone,

Today in this article we are going to learn about how to use “Navigation And Routing” in flutter project.

Introduction

This article will guide you on how to use navigation and routing for moving from one screen to another screen.

Any mobile app that allows users to switch between multiple pages must adhere to two fundamental concepts: navigation and routing.

We are aware that each mobile application has a variety of screens. Screens for showing various types of data. For instance, might include a screen showcasing a range of goods. When a user taps on a product, all the product’s details are immediately displayed.

In Flutter, the screens and pages are referred to as routes, which are merely widgets. A route is analogous to an Activity in Android, but it is equivalent to a ViewController in iOS.

Any mobile app’s workflow is determined by switching between pages, and the process of handling navigation is referred to as routing.
MaterialPageRoute() is a basic routing class in Flutter, with two methods to travel between two routes: Navigator.push() and Navigator.pop(). To get started with navigation in your app, you’ll need to take the steps below.

1)  Navigate using Navigator.push() & Navigator.pop().

Step 1: Foremost, you need to create 2 routes.

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

Step 3: Finally, using the Navigator, navigate to the first route. pop() is a method that returns a value.

Now, Create two widgets first is ‘RouteFirst’ & second is ‘RouteSecond’

Widget 1: RouteFirst

class RouteFirst extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text('Route First'),  
      ),  
      body: Center(  
        child: InkWell(  
          child: Text('Go to second widget'),  
          onTap: () {},  
        ),  
      ),  
    );  
  }  
}  

Widget 2: RouteSecond

class RouteSecond extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text("Second Route"),  
      ),  
      body: Center(  
        child: InkWell(  
          onTap: () { },  
          child: Text('Go back to the first widget'),  
        ),  
      ),  
    );  
  }  
}

Now, In first widget there is one method call onTap(){}. In that add push route code for navigate to the second widget.

onTap: () {  
  Navigator.push(  
    context,  
    MaterialPageRoute(builder: (context) => RouteSecond()),  
  );  
}  

Now, In second  widget there is one method call onTap(){}. In that add pop route code for navigate back to the first widget.

onTap: () {  
  Navigator.pop(context);  
} 

Let’s look at the complete code for navigating between two routes. Create a Flutter project and paste the code below into the main.dart file.

import 'package:flutter/material.dart';  
void main() {  
  runApp(MaterialApp(  
    title: 'Flutter Navigation',  
    home: RouteFirst(),  
  ),
);  
}  
  
class RouteFirst extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text('First'),  
      ),  
      body: Center(  
        child: InkWell(  
          child: Text(‘Click to go to the second widget’),  
          onTap: () {  
            Navigator.push(  
              context,  
              MaterialPageRoute(builder: (context) => RouteSecond()),  
            );  
          },  
        ),  
      ),  
    );  
  }  
}  
  
class RouteSecond extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text("Second"),  
      ),  
      body: Center(  
        child: InkWell(  
          onTap: () {  
            Navigator.pop(context);  
          },  
          child: Text('Click here for Go back'),  
        ),  
      ),  
    );  
  }  
}  

This two are main route for navigate from one screen to second screen.

Navigation with Named Routes

2) Navigation with Named Routes.

Now we are see how to navigate using names routes.

The Navigator.pushNamed() function allows us to interact with named routes. Build context and string are the two necessary arguments for this function, and one more argument is optional. We are also aware of the MaterialPageRoute, which controls page transition. It is challenging to alter the page if we don’t use this.

The following steps are importent, which provide named route usage examples.

Step 1: We must first make two screens. The two screens of our app are made using the following code.

class RouteFirst extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text(“Route First”),  
      ),  
      body: Center(  
        child: InkWell(  
          child: Text('Tap here to navigate.'),  
          color: Colors.orangeAccent,  
          onTap: () {  
            
          },  
        ),  
      ),  
    );  
  }  
}  
  
class RouteSecond extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text("Route Second"),  
      ),  
      body: Center(  
        child: InkWell(  
          color: Colors.blueGrey,  
          onTap: () {  
            
          },  
          child: Text('Go back from this screen'),  
        ),  
      ),  
    );  
  }  
}  

Step 2: Now define this route in materialApp widget.

We must specify the routes in this phase. The first route and other routes themselves must be defined in the MaterialApp function Object(). Here, the named routes and widgets that are available are defined by the routes property, while the initial route indicates where the page begins. More details are provided in the code below.

MaterialApp(  
  title: ‘Navigation’,  
  initialRoute: '/',  
  routes: {  
    '/': (context) => RouteFirst(),  
    '/second': (context) => RouteSecond(),  
  },  
);  

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

We must dial Navigator at this point. the navigational pushNamed() method.

onTap: () {  
  Navigator.pushNamed(context, '/second');  
}  

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

We will use Navigator in this final stage. On the first screen, use the pop() method to return.

onTap: () {  
  Navigator.pop(context);  
},

Let’s examine the complete source code for the aforementioned explanation in the Flutter project.

import 'package:flutter/material.dart';  
  
void main() {  
  runApp( MaterialApp(  
    title: 'Named Route Navigation',  
    theme: ThemeData(  
      // This is the theme of your application.  
      primarySwatch: Colors.green,  
    ),  
    // Start the app with the "/" named route. In this case, the app starts  
    // on the FirstScreen widget.  
    initialRoute: '/',  
    routes: {  
      // When navigating to the "/" route, build the FirstScreen widget.  
      '/': (context) => HomeScreen(),  
      // When navigating to the "/second" route, build the SecondScreen widget.  
      '/second': (context) => SecondScreen(),  
    },  
  ));  
}  
  
class HomeScreen extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text('Home Screen'),  
      ),  
      body: Center(  
        child: RaisedButton(  
          child: Text('Click Here'),  
          color: Colors.orangeAccent,  
          onPressed: () {  
            Navigator.pushNamed(context, '/second');  
          },  
        ),  
      ),  
    );  
  }  
}  
  
class SecondScreen extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text("Second Screen"),  
      ),  
      body: Center(  
        child: RaisedButton(  
          color: Colors.blueGrey,  
          onPressed: () {  
            Navigator.pop(context);  
          },  
          child: Text('Go back!'),  
        ),  
      ),  
    );  
  }  
}   

So, that’s how you can use Navigator and routing in your project.

Hope you guys found something useful. If you have any doubts or questions do comment.

See you in the Next Article.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories