How to check which the current Route is?

I want to navigate to different Routes using a Drawer, though I do not want to open a new instance of a Route each time I tap on it if I am already on that Route, rather I would prefer that in this case a new Route is not opened. This is my code so far:

Widget build(BuildContext context){
    return new Drawer(
      child:
          new ListView(
            children: <Widget>[
              new ListTile(
                title: new Text("NewRoute"),
                onTap: () {
                    Navigator.of(context).pop;
                    Navigator.of(context).pushNamed('/NewRoute');
                }
              )
           )
     )
}

I want to use a conditional statement to check whether we are on a certain route. I know there is a way to check which Route we are on currently with the isCurrent of the Route class

https://docs.flutter.io/flutter/widgets/Route/isCurrent.html

though I am not sure how to implement it.

Thank you in advance!


Navigator doesn't expose the current route.

What you can do instead is use Navigator.popUntil(callback) as popUtil pass to the callback the current Route, which includes it's name and stuff.

final newRouteName = "/NewRoute";
bool isNewRouteSameAsCurrent = false;

Navigator.popUntil(context, (route) {
  if (route.settings.name == newRouteName) {
    isNewRouteSameAsCurrent = true;
  }
  return true;
});

if (!isNewRouteSameAsCurrent) {
  Navigator.pushNamed(context, newRouteName);
}

This should give you the exact route name

import 'package:path/path.dart';

ModalRoute.of(context).settings.name

To avoid null exception do this

var route = ModalRoute.of(context);

if(route!=null){
    print(route.settings.name);
 }

This is a perfect use case for Dart extension methods (based on Rémi Rousselet's answer):

extension NavigatorStateExtension on NavigatorState {

  void pushNamedIfNotCurrent( String routeName, {Object arguments} ) {
    if (!isCurrent(routeName)) {
      pushNamed( routeName, arguments: arguments );
    }
  }

  bool isCurrent( String routeName ) {
    bool isCurrent = false;
    popUntil( (route) {
      if (route.settings.name == routeName) {
        isCurrent = true;
      }
      return true;
    } );
    return isCurrent;
  }

}

Then it looks as clean as this:

Navigator.of(context).pushNamedIfNotCurrent('/NewRoute');