How to check which the current Route is?

前端 未结 11 752
栀梦
栀梦 2021-02-03 17:49

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

11条回答
  •  我在风中等你
    2021-02-03 18:17

    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');
    

提交回复
热议问题