How to Get Current Route Path In Flutter

How to Get Current Route Path In Flutter?

In the Navigate to a new screen and back recipe, you learned how to navigate to a new screen by creating a new route and pushing it to the Navigator. In today’s article, we will go through how to get the current route path in flutter.

In this blog post, we’ll guide you through the process of obtaining the current route path in Flutter. Whether you’re building a navigation-heavy app or need to dynamically respond to route changes, understanding how to retrieve the current route path is crucial. We’ll explore different techniques and APIs provided by Flutter’s navigation framework to retrieve the current route path. You’ll learn how to leverage the Navigator class, RouteObserver, and MediaQuery to access and utilize the current route information effectively.

How to Get Current Route Path In Flutter?

If you need to navigate to the same screen in many parts of your app, this approach can result in code duplication. The solution is to define a named route, and use the named route for navigation.

To work with named routes, use the Navigator.pushNamed() function.

This should give you the exact route name

ModalRoute.of(context).settings.name

NavigatorState doesn’t expose an API for getting the path of the current route, and Route doesn’t expose an API for determining a route’s path either. Routes can be (and often are) anonymous. You can find out if a given Route is on the top of the navigator stack right now using the isCurrent method, but this isn’t very convenient for your use case.

I would recommend that you take a different approach to this problem and don’t rewind to the root at all. Instead, use a different Navigator widget for each pane of the BottomNavigationBar.

That way, you won’t have to rewind the stack when switching between panes.

You can wrap your Navigator widgets in Opacity and IgnorePointer widgets to hide them when they aren’t supposed to be visible without destroying their stack.

We will get output like a below:

get current route path
get current route path

Our code snippet will look like the below:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class SecurePage extends StatelessWidget {
  final int index;

  SecurePage(this.index);

  Widget build(BuildContext context) {
    return new Material(
      color: Colors.amber,
      child: new InkWell(
        child: new Center(
          child: new Icon(
            Icons.security,
            color: Colors.white,
            size: index * 100.0 + 20.0,
          ),
        ),
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (BuildContext context) {
                return new SecurePage(index + 1);
              },
            ),
          );
        },
      ),
    );
  }
}

class VerifiedPage extends StatelessWidget {
  final int index;

  VerifiedPage(this.index);

  Widget build(BuildContext context) {
    return new Material(
      color: Colors.green,
      child: new InkWell(
        child: new Center(
          child: new Icon(
            Icons.verified_user,
            color: Colors.white,
            size: index * 100.0 + 20.0,
          ),
        ),
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (BuildContext context) {
                return new VerifiedPage(index + 1);
              },
            ),
          );
        },
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  int _page = 0;
  List<Widget> initialWidgets = <Widget>[
    new SecurePage(0),
    new VerifiedPage(0),
  ];

  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Stack(
        children: new List<Widget>.generate(initialWidgets.length, (int index) {
          return new IgnorePointer(
            ignoring: index != _page,
            child: new Opacity(
              opacity: _page == index ? 1.0 : 0.0,
              child: new Navigator(
                onGenerateRoute: (RouteSettings settings) {
                  return new MaterialPageRoute(
                    builder: (_) => initialWidgets[index],
                  );
                },
              ),
            ),
          );
        }),
      ),
      bottomNavigationBar: new BottomNavigationBar(
        currentIndex: _page,
        onTap: (int index) {
          setState(() {
            _page = index;
          });
        },
        items: <BottomNavigationBarItem>[
          new BottomNavigationBarItem(
            icon: new Icon(Icons.security),
            label: 'Secure',
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.verified_user),
            label: 'Verified',
          ),
        ],
      ),
    );
  }
}

To get the current route name example /home or /page try this

ModalRoute.of(context).settings.name

Extra Points

In Flutter, obtaining the current route path can vary depending on the navigation approach used in your application. For traditional navigation with Navigator 1.0, you can use the ModalRoute.of(context) method to access the route settings and retrieve the route name:

Dart code

String currentRouteName = ModalRoute.of(context)?.settings.name ?? 'Unknown';

However, with the advent of Navigator 2.0 and advanced routing packages like go_router, the methodology shifts towards a more declarative and state-managed approach. In these scenarios, the concept of a “current route” is often managed within your application’s state, rather than being directly queried from the widget tree. This reflects the Navigator 2.0’s emphasis on a more flexible and programmable route-handling system.

For those utilizing Navigator 2.0 or other modern routing solutions, tracking the current route involves managing the navigation state through higher-level application state mechanisms, rather than relying on direct queries. This evolution in routing practices underscores the importance of adapting to the latest Flutter navigation paradigms for efficient and scalable app development.

Conclusion:

Thanks for reading!!

Keep Learning!!! Keep fluttering!!!

So in this article, we have been through how to get the current route path in the flutter.

Do let us know if you are still confused in the flutter. We would love to assist you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields